42

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?

3
  • As Alex N. says, escapeshellarg is what you're looking for, but I would strongly consider assigning known to be safe filenames and mapping them through you database, potentially to user-friendly filenames.
    – Steven
    Nov 27, 2010 at 3:09
  • 1
    worse: imagine a firstname of "/../../../etc/passwd"
    – Greg
    Feb 3, 2012 at 16:55
  • Generally speaking "." and ".." are important to consider as well.
    – asmecher
    Sep 20, 2013 at 18:33

3 Answers 3

85

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

4
  • 5
    dash at the end (or start) are not considered as a range indicator
    – luxcem
    Sep 4, 2013 at 7:53
  • 5
    Using this way, dot between file name and file extension will be escaped too.
    – SAMPro
    Jul 6, 2014 at 19:17
  • 1
    @SAMPro true, but it is a file NAME we are talking about, you should always make your own extension after checking MIME-TYPE some reliable way (e.g. Fileinfo module)
    – jave.web
    Sep 25, 2014 at 5:15
  • 5
    /[^\w-]/ is enough !
    – Drasill
    Mar 30, 2016 at 16:45
15

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);
3
  • 1
    I was worried there were other symbols that could be dangerous - hopefully / is the only issue. Nov 27, 2010 at 3:12
  • 6
    escapeshellarg and such is only useful when sending shell commands (using shell_exec, exec and such), to ensure that other operators (like ;, && or backticks) are escaped, in order to prevent shell command injection (similar to SQL injection, but in a shell, and WAY more harmful). PHP's filesystem functions (fopen, file_put_contents and such) don't have to escape filenames. Worst case scenario in your situation (i.e.: without str_replace), PHP will fail to write the file with a "No such file or directory" error.
    – netcoder
    Nov 27, 2010 at 3:16
  • 3
    The OS might also disallow certain characters within filenames (for instance, Windows does not allow the colon :, as well as various other characters), which is a problem that this answer does not solve. If you're not sure what server environment your code will run on, Tommy Lacroix's answer is far superior.
    – JMTyler
    Apr 20, 2014 at 18:21
3

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

5
  • 8
    "." and ".." can cause trouble too.
    – asmecher
    Sep 20, 2013 at 17:58
  • 6
    . and .. are harmless without the /. Sep 20, 2013 at 18:18
  • 1
    ...but are still reserved names and IMO ought to be considered.
    – asmecher
    Sep 20, 2013 at 18:44
  • 12
    . can be harmful if it's your whole filename. For example, rmdir(realpath($pathToWeb . '../uploads/' . $userInput)) or some similar situation Jan 27, 2014 at 23:09
  • 3
    You should thus use $filename = preg_replace('((^\.)|\/|(\.$))', '_', $filename) -- which escapes any slash and every dot at the start or end.
    – caw
    Sep 27, 2014 at 20:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.