PHP: How to clear downloaded file names?

I have a PHP application.

I allow users to upload files to my web application.

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

UPDATE

Can I take MD5 of the downloaded file name and use it as the new assigned file name? If so, how to do it in PHP?

+6
php file-upload sanitization
source share
6 answers

To avoid clashing with file names, just check to see if the given or generated file name is specified:

 do { // Generate filename, eg.: $filename = md5(uniqid()) . $fileExtension; } while (file_exists($filename)); 

This gives you 100% confidence that the file name is unique. Using md5 (or any other hashing algorithm) ensures that the file name is safe - and easy to handle.

+4
source share

I bet you also store some file information in the database. If this is correct, you can use the primary key (ID) as the file name on your server and save the original file name in the database. This gives you more flexibility since you can manipulate metadata without renaming the actual file.

+3
source share

I just run a simple regular expression that replaces any non-alphanumeric characters with an underscore (or just removes that character altogether). Be sure to save the extension, of course.

If you want to go a little further, you can use the magic mime extension to ensure that the file is the same format the extension speaks of.

EDIT: To avoid file name conflicts in a directory, you can add md5 users IP + current time to the file name.

+2
source share

Instead of sanitizing the user-specified file names, use any other unique identifier for this photo and save this file name. I prefer to use a user id that is numeric and always unique.

move_uploaded_file($_FILES["tmp_name"],"/home/yourname/".$user_id));

Then you can get the image from anywhere (for example, S3 or even your own server), just knowing the user ID. You don't even need an attribute in your database to store image URLs.

0
source share

Ciao, this function also deletes all points, and then I create a clean line with the extension.

 function sanitaze_upload_file($data) { $imgName = $data; $indexOFF = strrpos($imgName, '.'); $nameFile = substr($imgName, 0,$indexOFF); $extension = substr($imgName, $indexOFF); $clean = preg_replace("([^\w\s\d\-_~,;\[\]\(\)])", "", $nameFile); $NAMEFILE = str_replace(' ', '', $clean).$extension; return $NAMEFILE; } 
0
source share

If you don't mind losing the actual file names, what I usually do is create a hash of the file name and set the file name for it, if all you develop is loading a lot of uploaded images, it helps to avoid conflicts when two file names are called same, and overwriting occurs.

 hash('md5', $_FILES["filename"]["tmp_name"]); 
-2
source share

All Articles