validate_file()
云策文档标注
概述
validate_file() 函数用于验证文件路径和名称是否符合允许的规则集,返回整数值表示验证结果。该函数主要用于防止目录遍历和 Windows 驱动路径等安全风险。
关键要点
- 函数接受两个参数:$file(必需,文件路径字符串)和 $allowed_files(可选,允许的文件数组,默认为空数组)。
- 返回值为整数:0 表示路径正常,大于 0 表示存在问题(1 表示包含目录遍历,2 表示包含 Windows 驱动路径,3 表示文件不在允许列表中)。
- 函数内部使用 wp_normalize_path() 对路径进行规范化处理,确保跨平台一致性。
- 验证规则包括:禁止单独的 '../'、禁止多个 '../' 出现、禁止 '../' 不在路径末尾、禁止不在允许列表中的文件、禁止绝对 Windows 驱动路径。
代码示例
// 有效文件路径示例
$path = 'uploads/2012/12/my_image.jpg';
return validate_file( $path ); // 返回 0(有效路径)。
// 无效文件路径示例
$path = '../../wp-content/uploads/2012/12/my_image.jpg';
return validate_file( $path ); // 返回 1(无效路径)。
原文内容
Validates a file name and path against an allowed set of rules.
Description
A return value of 1 means the file path contains directory traversal.
A return value of 2 means the file path contains a Windows drive path.
A return value of 3 means the file is not in the allowed files list.
Parameters
$filestringrequired-
File path.
$allowed_filesstring[]optional-
Array of allowed files.
Default:
array()
Source
function validate_file( $file, $allowed_files = array() ) {
if ( ! is_scalar( $file ) || '' === $file ) {
return 0;
}
// Normalize path for Windows servers.
$file = wp_normalize_path( $file );
// Normalize path for $allowed_files as well so it's an apples to apples comparison.
$allowed_files = array_map( 'wp_normalize_path', $allowed_files );
// `../` on its own is not allowed:
if ( '../' === $file ) {
return 1;
}
// More than one occurrence of `../` is not allowed:
if ( preg_match_all( '#../#', $file, $matches, PREG_SET_ORDER ) && ( count( $matches ) > 1 ) ) {
return 1;
}
// `../` which does not occur at the end of the path is not allowed:
if ( str_contains( $file, '../' ) && '../' !== mb_substr( $file, -3, 3 ) ) {
return 1;
}
// Files not in the allowed file list are not allowed:
if ( ! empty( $allowed_files ) && ! in_array( $file, $allowed_files, true ) ) {
return 3;
}
// Absolute Windows drive paths are not allowed:
if ( ':' === substr( $file, 1, 1 ) ) {
return 2;
}
return 0;
}
Changelog
| Version | Description |
|---|---|
| 1.2.0 | Introduced. |
Skip to note 2 content
Codex
Valid file path
$path = 'uploads/2012/12/my_image.jpg'; return validate_file( $path ); // Returns 0 (valid path).Invalid file path
$path = '../../wp-content/uploads/2012/12/my_image.jpg'; return validate_file( $path ); // Returns 1 (invalid path).