validate_file()验证文件是否存在

目录

描述

Used to prevent directory traversal attacks, or to test a filename against a whitelist.

validate_file() 描述

用法

/* ----------------------------------
 * wordpress之魂 © http://wphun.com
 * ---------------------------------- */
<?php validate_file( $file, $allowed_files ); ?>

validate_file() 用法

参数

$file

(string) (必填) The file path.

默认值: None

$allowed_files

(array) (可选) An array of allowed files

默认值: null

validate_file() 参数

返回值

(0) 

$file represents a valid relative path. You must treat it as a relative path after validating.

(1) 

$file is invalid and contains either '..' or './'

(2) 

$file is invalid and contains ':' after the first character.

(3) 

$file is invalid and is not in the $allowed_file list.

validate_file() 返回值

示例

/* ----------------------------------
 * wordpress之魂 © http://wphun.com
 * ---------------------------------- */
$path = 'uploads/2012/12/my_image.jpg';
return validate_file( $path ); // returns 0 (valid path)
/* ----------------------------------
 * wordpress之魂 © http://wphun.com
 * ---------------------------------- */
$path = '../../wp-content/uploads/2012/12/my_image.jpg';
return validate_file( $path ); // returns 1 (invalid path)

validate_file() 示例

注意

Be careful making boolean interpretations of the result, since false (0) indicates the filename has passed validation, whereas true (> 0) indicates failure.

validate_file() 注意

源文件

validate_file() 函数的代码位于 wp-includes/functions.php.

/* ----------------------------------
 * wordpress之魂 © http://wphun.com
 * ---------------------------------- */
/**
 * File validates against allowed set of defined rules.
 *
 * A return value of '1' means that the $file contains either '..' or './'. A
 * return value of '2' means that the $file contains ':' after the first
 * character. A return value of '3' means that the file is not in the allowed
 * files list.
 *
 * @since 1.2.0
 *
 * @param string $file File path.
 * @param array  $allowed_files List of allowed files.
 * @return int 0 means nothing is wrong, greater than 0 means something was wrong.
 */
function validate_file( $file, $allowed_files = '' ) {
	if ( false !== strpos( $file, '..' ) )
		return 1;

	if ( false !== strpos( $file, './' ) )
		return 1;

	if ( ! empty( $allowed_files ) && ! in_array( $file, $allowed_files ) )
		return 3;

	if (':' == substr( $file, 1, 1 ) )
		return 2;

	return 0;
}

validate_file() 源文件

相关