What is the best way to sanitize $_GET['']
request? I want to allow downloading files from one directory only.
$baseDir = "/home/html/xy.com/public_html/downloads/";
$path = realpath($baseDir . $_GET['file']);
What is the next step?
Here's what I would do after the lines you have there:
if (dirname($path) === $baseDir) {
//Safe
}
http://php.net/dirname
Basically, do a check before sending anything that the file is actually in that one path you support. Note, you will also have to add your own /
before the filename (in $path
) and remove it from your $baseDir
definition, as dirname()
won't leave a trailing path separator.
Instead of post-checking that no relative path fragments were present, it's easier to just strip them right away. Just use basename()
immediately when you fetch the value:
$baseDir = "/home/html/xy.com/public_html/downloads/";
$path = realpath($baseDir . basename($_GET['file']));
That already guarantees that it can't move upwards or downwards from your base directory.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With