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.
-
6As a side note, this isn't really checking if the file name is "valid". It's simply stripping out anything up to and including the last PHP directory separator. I understand the OP's intent was to do that. But others may think this validates something - and it does not. – Lee Fuller Dec 2 '15 at 22:09
-
3
$file = '../../abc\text.txt'; echo basename($file);
will echoabc\text.txt
and it's not a valid filename. – mechanicious Aug 12 '18 at 8:03
POSIX "Fully portable filenames" lists these: A-Z
a-z
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_]
-
.
$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\-. ]+$/'
.
Would that work? http://php.net/manual/en/function.file-exists.php E.g, 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.
-
Work fine too but I think kamal pal's version is more compact and I don't want to go to subfolder.. But thank you too <3 – askerno Jun 27 '15 at 13:48
i will like to combine kamal pal's and Pancake_M0nster's answers to create simple:
if(file_exists(basename($file))){
// valid
}
else{
// invalid
}
-
1Combining two different solutions doesn't always provide a better or more efficient answer. Sometimes, it even breaks the functionality: in this case, the result would be "true" only if the
$file
resides in the same directory as the main script. – Erenor Paz Mar 6 '18 at 8:28
/
– adeneo Jun 27 '15 at 13:41