Safer php filenames
2009-10-18 22:09So you’re storing user files in your PHP app, but you are worried about security (as you should). Two bad things you might encounter (amongst others): a filename with “../” so as to overwrite arbitrary files on your server, or a filename with .php in it (to run arbitrary code).
I read this idea, but his method didn’t cut it for me.
Here’s a better one:
$str = preg_replace(array('/[^A-Za-z0-9_\-.]/', '/.php/'), '_', $str);
This nukes anything that’s not Alphanumeric or -,.,_. It also nukes any .php sequences.
For this I think a whitelist is better than a blacklist. Should I block anything else out?
Test case:
$str = '../tryToOverWiteMyScriptNow.php';
$str = preg_replace(array('/[^A-Za-z0-9_\-.]/', '/.php/'), '_', $str);
echo $str;


