munchybunch
munchybunch

Reputation: 6153

PHP escape user input for filename

I have a form where users can upload files, and I'd like to name the file something along the lines of [id]_[lastname]_[firstname].pdf. The name is entered by the user, and I'm afraid of them entering something with a slash in it. Otherwise, something like $path = $dir.$filename could result in $path = 'uploads/2_smith_john/hahaimajerk.pdf' if the firstname is john/hahaimajerk.

I don't really want to force users to restrict their names to anything; I don't mind changing their names a little in the file name as long as I can tell the original name. What characters do I need to escape, or is there some other way to do this? Or...do I just use mysql_real_escape_string?

Upvotes: 44

Views: 39309

Answers (3)

Tommy Lacroix
Tommy Lacroix

Reputation: 1553

I usually use regular expressions for this. And instead of removing certain specific characters (like slashes, dots, etc), I prefer to only allow certain characters (like alphanumeric)

For instance, this will replace any character that is not a letter, a number, a dash or an underscore by an underscore:

$escaped = preg_replace('/[^A-Za-z0-9_\-]/', '_', $raw);

The backslash before the dash is to escape the dash in the regular expression, as dashes are otherwise used to specify character ranges (such as A-Z).

Upvotes: 87

netcoder
netcoder

Reputation: 67695

mysql_real_escape_string won't escape slashes. Even escapeshellarg won't do it. You will have to use str_replace:

$path = str_replace('/', '_', $path);

Upvotes: 15

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324640

The only "unsafe" character in a filename is / - so you can easily avoid problems by using str_replace("/","",$filename)

Upvotes: 3

Related Questions