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