W3cubDocs

/WordPress

validate_file( string $file, array $allowed_files = array() )

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

$file

(string) (Required) File path.

$allowed_files

(array) (Optional) List of allowed files.

Default value: array()

Return

(int) 0 means nothing is wrong, greater than 0 means something was wrong.

Source

File: wp-includes/functions.php

function validate_file( $file, $allowed_files = array() ) {
	// `../` on its own is not allowed:
	if ( '../' === $file ) {
		return 1;
	}

	// More than one occurence 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 ) ) {
		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.

© 2003–2019 WordPress Foundation
Licensed under the GNU GPLv2+ License.
https://developer.wordpress.org/reference/functions/validate_file