函数文档

wp_check_filetype()

💡 云策文档标注

概述

wp_check_filetype() 函数用于从文件名中检索文件类型,包括扩展名和 MIME 类型。它支持自定义 MIME 类型数组进行匹配检查。

关键要点

  • 函数接受两个参数:$filename(必需,文件名或路径)和 $mimes(可选,允许的 MIME 类型数组,默认为 get_allowed_mime_types() 的结果)。
  • 返回一个数组,包含 ext(文件扩展名或 false)和 type(MIME 类型或 false),如果文件不匹配任何 MIME 类型则返回 false。
  • 内部通过正则表达式遍历 $mimes 数组来匹配文件名,找到第一个匹配项即停止。

代码示例

function wp_check_filetype( $filename, $mimes = null ) {
	if ( empty( $mimes ) ) {
		$mimes = get_allowed_mime_types();
	}
	$type = false;
	$ext  = false;

	foreach ( $mimes as $ext_preg => $mime_match ) {
		$ext_preg = '!.(' . $ext_preg . ')$!i';
		if ( preg_match( $ext_preg, $filename, $ext_matches ) ) {
			$type = $mime_match;
			$ext  = $ext_matches[1];
			break;
		}
	}

	return compact( 'ext', 'type' );
}

📄 原文内容

Retrieves the file type from the file name.

Description

You can optionally define the mime array, if needed.

Parameters

$filenamestringrequired
File name or path.
$mimesstring[]|nulloptional
Array of allowed mime types keyed by their file extension regex.
Defaults to the result of get_allowed_mime_types() .

Default:null

Return

array Values for the extension and mime type.

  • ext string|false
    File extension, or false if the file doesn’t match a mime type.
  • type string|false
    File mime type, or false if the file doesn’t match a mime type.

Source

function wp_check_filetype( $filename, $mimes = null ) {
	if ( empty( $mimes ) ) {
		$mimes = get_allowed_mime_types();
	}
	$type = false;
	$ext  = false;

	foreach ( $mimes as $ext_preg => $mime_match ) {
		$ext_preg = '!.(' . $ext_preg . ')$!i';
		if ( preg_match( $ext_preg, $filename, $ext_matches ) ) {
			$type = $mime_match;
			$ext  = $ext_matches[1];
			break;
		}
	}

	return compact( 'ext', 'type' );
}

Changelog

Version Description
2.0.4 Introduced.

User Contributed Notes