Which characters should I escape/sanitize for file names?

php

Solution

If you have the opportunity to store the original name in a database I would simply create a file with a random hash (mt_rand()/md5/sha1). The benefit would be that you don't rely on the underlying OS (characters/path length), the value or the length of the user input and additionally it is really hard to guess/forge a file name. Maybe even a base64 encoding is an option.

Problem

I need to sanitize some data which will be used in file names. Some of the data contains spaces and ampersand characters. Is there a function which will escape or sanitize data suitable for using in a file name (or path)? I couldn't find one in the 'Filesystem Function' section of the PHP manual. So, assuming I have to write my own function, which characters do I need to escape (or change)?

Original source