Sanitising uploaded filenames
Because of the differences in the way Linux and Windows systems handle filenames, and because users often upload files which have spaces, quotes, and other punctuation characters in the name, it's important that you strip out these characters from the filename before saving the file on the webserver.
Here's one way of doing it:
function sanitise($text) {
$text = preg_replace('/[\s]+/', ' ', preg_replace('/[^a-z0-9.]/i', ' ', $text));
$text = strtolower(str_replace(' ', '-', trim(trim($text, '.'))));
return $text;
}
In plain English, these are the rules applied by the sanitise() function above:
- Keep alphanumerics and dots and convert the rest to spaces.
- Strip excessive spaces.
- Convert the remaining spaces to dashes.
- Strip any leading and trailing spaces and dots.
- Convert everything to lowercase.
So, a filename like this:
../RiDIculous '~= +(& looKing_FILEname.jpg.
Ends up being this:
ridiculous-looking-filename.jpg
It's easy to read and won't cause any problems to users who attempt to download it. The conversion to lowercase is purely based on my principles of aesthetics and isn't strictly required, so you may remove that if you wish.
Due to the large volume of spam, comments are disabled. If you have anything relevant to say, you can leave a , or contact me directly.