validate_file()WP 1.2.0

Validates a file name and path against an allowed set of rules.

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.

1 time — 0.000018 sec (very fast) | 50000 times — 0.01 sec (speed of light) | PHP 7.1.2, WP 4.7.5

No Hooks.

Return

Int. 0 means nothing is wrong, greater than 0 means something was wrong.

Usage

validate_file( $file, $allowed_files );
$file(string) (required)
File path.
$allowed_files(string[])
Array of allowed files.
Default: array()

Examples

0

#1 Demo of file path checks

A path that will pass inspection:

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

A path that will not pass inspection:

$path = '../../wp-content/uploads/2012/12/my_image.jpg';
echo validate_file( $path ); // print 1 (inaccessible path)

Changelog

Since 1.2.0 Introduced.

validate_file() code WP 6.1.1

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 ( false !== strpos( $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;
}