简体   繁体   中英

Check if string is valid filename

I have a question. I got a PHP script (PHP 5) which is saving a URL-Parameter $_GET['file'] to the variable $file . Is there now a way to check if this variable is a valid filename (for example: hello.txt and not /../otherdir/secret.txt ). Because without checking the $file variable a hacker would be able to use the /../ to get to my parent folder.

You may have a look in php's basename function, it will return with filename, see example below:

$file = '../../abc.txt';
echo basename($file); //output: abc.txt

Note: basename gets you the file name from path string irrespective of file physically exists or not. file_exists function can be used to verify that the file physically exists.

POSIX "Fully portable filenames" lists these: AZ az 0-9 . _ -

Use this code to validate the filename against POSIX rules using regex:

  • / - forward slash (if you need to validate a path rather than a filename)
  • \\w - equivalent of [0-9a-zA-Z_]
  • - . - dash dot space
$filename = '../../test.jpg';
if (preg_match('/^[\/\w\-. ]+$/', $filename)) 
    echo 'VALID FILENAME'; 
else 
    echo 'INVALID FILENAME';

If you want to ensure it has no path (no forwardslash) then change the regex to '/^[\\w\\-. ]+$/' '/^[\\w\\-. ]+$/' .

Instead of checking valid characters why not looking for character you don't want . Also filenames are limited to 255 characters:

function valid_filename(string $filename)
{
  if (strlen($filename) > 255) { // no mb_* since we check bytes
    return false;
  }
  $invalidCharacters = '|\'\\?*&<";:>+[]=/';
  if (false !== strpbrk($filename, $invalidCharacters)) {
    return false;
  }
  return true;
}


valid_filename('hello');       // true
valid_filename('hello.php');   // true
valid_filename('foo:bar.php'); // false
valid_filename('foo/bar');     // false

Adapt $invalidCharacters according to your needs/OS.

Source: https://www.cyberciti.biz/faq/linuxunix-rules-for-naming-file-and-directory-names/

Would that work? http://php.net/manual/en/function.file-exists.php Eg, in your case,

if(file_exists(str_replace("../", "", $file))){
  // valid
} 
else{
  // invalid
}

Files can be in subfolders but not in parent folders.

However, if you're just interested in the filename,

if(file_exists(pathinfo($file, PATHINFO_BASENAME))){
  // valid
}
else{
  // invalid
}

should work.

i will like to combine kamal pal's and Pancake_M0nster's answers to create simple:

if(file_exists(basename($file))){
  // valid
} 
else{
  // invalid
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM