wpseek.com
A WordPress-centric search engine for devs and theme authors



validate_file › WordPress Function

Since1.2.0
Deprecatedn/a
validate_file ( $file, $allowed_files = array() )
Parameters: (2)
  • (string) $file File path.
    Required: Yes
  • (string[]) $allowed_files Optional. Array of allowed files. Default empty array.
    Required: No
    Default: array()
Returns:
  • (int) 0 means nothing is wrong, greater than 0 means something was wrong.
Defined at:
Codex:
Change Log:
  • 7.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 an absolute Windows path. This covers drive paths such as C:/WINDOWS, UNC network share paths such as //server/share, and the Windows device namespaces //./ and //?/. A return value of 3 means the file is not in the allowed files list. Note that absolute POSIX paths such as /etc/passwd are not rejected, and never have been. Callers that must reject them are responsible for their own check. The convention in core is to concatenate the validated value onto a trusted base directory and then confirm the result exists, rather than to treat this function as an absolute-path guard.


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 paths are not allowed.
	 *
	 * The drive-letter test predates validate_file() itself, arriving from
	 * b2/cafelog by way of a long series of moves. It only ever matched the
	 * `X:` form, which left UNC and device paths accepted: wp_normalize_path()
	 * above has already folded backslashes to forward slashes, and it
	 * deliberately preserves a leading `//` for network shares, so those
	 * paths arrive with no colon in the second byte.
	 *
	 * Anchoring the second test to the start of the string is what keeps
	 * stream wrappers working. A registered wrapper keeps its `://` through
	 * wp_normalize_path(), placing those slashes past the second byte.
	 */
	if ( ':' === substr( $file, 1, 1 ) || str_starts_with( $file, '//' ) ) {
		return 2;
	}

	return 0;
}