WordPress函数:validate_file 验证文件路径

江河/ 01月15日/ WordPress/ 浏览 335

函数原型:


validate_file( string $file, string[] $allowed_files = array() ): int


根据允许的一组规则验证文件名和路径。只验证路径是否正确,并不验证文件是否真实存在。


参数说明:


$file 要验证的文件路径


$allowed_files 允许的文件路径


返回值:


0 路径正确


1 路径包含目录遍历。


2 路径包含Windows驱动器路径。


3 该文件不在允许的文件列表中。


函数源码:


function validate_file( $file, $allowed_files = array() ) {
	if ( ! is_scalar( $file ) || '' === $file ) {
		return 0;
	}

	// `../` 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;
}


使用举例:


$path = 'uploads/2012/12/my_image.jpg';
return validate_file( $path ); // Returns 0 (valid path).


$path = '../../wp-content/uploads/2012/12/my_image.jpg';
return validate_file( $path ); // Returns 1 (invalid path).


发表评论

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

客服 工单