file_check_location

5 file.inc file_check_location($source, $directory = '')
6 file.inc file_check_location($source, $directory = '')

Check if a file is really located inside $directory. Should be used to make sure a file specified is really located within the directory to prevent exploits.

  // Returns FALSE:
  file_check_location('/www/example.com/files/../../../etc/passwd', '/www/example.com/files');

Parameters

$source A string set to the file to check.:

$directory A string where the file should be located.:

Return value

0 for invalid path or the real path of the source.

Related topics

1 call to file_check_location()

File

includes/file.inc, line 191
API for handling file uploads and server file management.

Code

function file_check_location($source, $directory = '') {
  $check = realpath($source);
  if ($check) {
    $source = $check;
  }
  else {
    // This file does not yet exist
    $source = realpath(dirname($source)) . '/' . basename($source);
  }
  $directory = realpath($directory);
  if ($directory && strpos($source, $directory) !== 0) {
    return 0;
  }
  return $source;
}

Comments

symlinks not allowed

It should be noted that this function does not consider symlinks to be "inside" the directory.

If you have

/somewhere/else/file.txt (a file)
/some/dir -> /somewhere/else (a symlink)

then

file_check_location('/some/dir/file.txt', '/some/dir')

will return 0.

Login or register to post comments