In PHP, I need use a user’s input as the title of a folder.
For example:
$foldername = $_REQUEST["foldername"];
mkdir("./userfolders/".$foldername);
Because, one problem I see with this is that the input could contain a “../” which would cause the folder to be written in the parent directory, which I don’t want. My solution to this was to str_replace away all forward slashes from the string.
Are there any other vulnerabilities that I’ve missed?
The ideal way would be not to accept user input for this at all IMO. Apart from other vulnerabilities depending on the file system (what about Windows’s backslashes, for example?) you may run into a world of other problems like character set trouble – think about
♥♥♥♥♥♥♥♥♥♥♥, for example: it’s a perfectly valid UTF-8 string….If you have a database at hand, a more secure way would be storing the user input there, and naming the directories after the database record’s unique ID for example.
If that’s not practical: one acceptable compromise that I’ve always liked is
urlencode()ing the user input, which will guarantee you won’t get problematic characters in the file system. You still need to be clear about which encoding you use (otherwise theurldecode()that you use afterwards to display the directory name will return broken data) but otherwise, this should work okay. The directories created this way will also be accessible through a browser, as special characters in a URL geturlencode()d anyway.