WordPress函数:sanitize_file_name 剔除文件名中的不允许使用的字符

江河/ 01月20日/ WordPress/ 浏览 1431

函数原型:


sanitize_file_name( string $filename ): string


对文件名进行消毒,用短划线替换空白。


删除某些操作系统上文件名中非法的特殊字符,以及需要特殊转义才能在命令行操作的特殊字符。将空格和连续的短划线替换为单个短划线。从文件名的开始和结束处修剪句点、短划线和下划线。不能保证此函数会返回允许上载的文件名。


参数说明:


要处理的文件名


返回值:


 处理后的文件名


函数源码:


function sanitize_file_name( $filename ) {
	$filename_raw = $filename;
	$filename     = remove_accents( $filename );

	$special_chars = array( '?', '[', ']', '/', '\\', '=', '<', '>', ':', ';', ',', "'", '"', '&', '$', '#', '*', '(', ')', '|', '~', '`', '!', '{', '}', '%', '+', '’', '«', '»', '”', '“', chr( 0 ) );

	// Check for support for utf8 in the installed PCRE library once and store the result in a static.
	static $utf8_pcre = null;
	if ( ! isset( $utf8_pcre ) ) {
		// phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
		$utf8_pcre = @preg_match( '/^./u', 'a' );
	}

	if ( ! seems_utf8( $filename ) ) {
		$_ext     = pathinfo( $filename, PATHINFO_EXTENSION );
		$_name    = pathinfo( $filename, PATHINFO_FILENAME );
		$filename = sanitize_title_with_dashes( $_name ) . '.' . $_ext;
	}

	if ( $utf8_pcre ) {
		$filename = preg_replace( "#\x{00a0}#siu", ' ', $filename );
	}

	$special_chars = apply_filters( 'sanitize_file_name_chars', $special_chars, $filename_raw );

	$filename = str_replace( $special_chars, '', $filename );
	$filename = str_replace( array( '%20', '+' ), '-', $filename );
	$filename = preg_replace( '/\.{2,}/', '.', $filename );
	$filename = preg_replace( '/[\r\n\t -]+/', '-', $filename );
	$filename = trim( $filename, '.-_' );

	if ( ! str_contains( $filename, '.' ) ) {
		$mime_types = wp_get_mime_types();
		$filetype   = wp_check_filetype( 'test.' . $filename, $mime_types );
		if ( $filetype['ext'] === $filename ) {
			$filename = 'unnamed-file.' . $filetype['ext'];
		}
	}

	// Split the filename into a base and extension[s].
	$parts = explode( '.', $filename );

	// Return if only one extension.
	if ( count( $parts ) <= 2 ) {
		return apply_filters( 'sanitize_file_name', $filename, $filename_raw );
	}

	// Process multiple extensions.
	$filename  = array_shift( $parts );
	$extension = array_pop( $parts );
	$mimes     = get_allowed_mime_types();

	foreach ( (array) $parts as $part ) {
		$filename .= '.' . $part;

		if ( preg_match( '/^[a-zA-Z]{2,5}\d?$/', $part ) ) {
			$allowed = false;
			foreach ( $mimes as $ext_preg => $mime_match ) {
				$ext_preg = '!^(' . $ext_preg . ')$!i';
				if ( preg_match( $ext_preg, $part ) ) {
					$allowed = true;
					break;
				}
			}
			if ( ! $allowed ) {
				$filename .= '_';
			}
		}
	}

	$filename .= '.' . $extension;

	return apply_filters( 'sanitize_file_name', $filename, $filename_raw );
}


包含钩子:


apply_filters( ‘sanitize_file_name’, string $filename, string $filename_raw )

apply_filters( ‘sanitize_file_name_chars’, string[] $special_chars, string $filename_raw )


使用举例:


$sanfilename = sanitize_file_name('[test],.php');
echo $sanfilename;


发表评论

暂无评论,抢个沙发...

客服 工单