18 Oct 2009, 10:09pm

leave a comment

Safer php filenames

So 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;

2 Oct 2009, 4:23pm

3 comments

3 Reasons to Buy a Samsung

3 Reasons to buy a Samsung

from a promo tent near XuJiaHui