Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP escape user input for filename

Tags:

php

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?

like image 752
munchybunch Avatar asked Nov 27 '10 03:11

munchybunch


2 Answers

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).

like image 126
Tommy Lacroix Avatar answered Oct 06 '22 01:10

Tommy Lacroix


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); 
like image 38
netcoder Avatar answered Oct 06 '22 00:10

netcoder