PHP: How to sanitize uploaded filenames?

frooyo picture frooyo · Sep 21, 2010 · Viewed 12.8k times · Source

I have a PHP application.

I allow users to upload files to my web application.

Question: What's the best way for me to sanitize the file names of the uploaded documents $_FILES["filename"]["tmp_name"] in PHP?

UPDATE:

Can I take an MD5 of the uploaded filename and use that as the newly assigned filename? If so, how do I do that in PHP?

Answer

Adam Byrtek picture Adam Byrtek · Sep 21, 2010

I bet that you also store some information about the file in the database. If this is correct, then you can use the primary key (ID) as a filename on your server and preserve the original filename in the database. This gives you greater flexibility, because you can manipulate the metadata without renaming the actual file.