I've been reading up on PHP file upload security and a few articles have recommended renaming the files. For example, the OWASP article Unrestricted File Upload says:
It is recommended to use an algorithm to determine the filenames. For instance, a filename can be a MD5 hash of the name of file plus the date of the day.
If a user uploads a file named Cake Recipe.doc
is there really any reason to rename it to 45706365b7d5b1f35
?
If the answer is yes, for whatever reason, then how do you keep track of the original file name and extension?
Renaming a file -- even changing the file extension -- should not affect the content of the file.
Answer: Renaming your files gives you that chance to look at the file again, whether it is in iPhoto, Windows Media Gallery, wherever. 4) File names are picked up by search engines.
When you rename a file, only the first part of the name of the file is selected, not the file extension (the part after the last .). The extension normally denotes what type of file it is (for example, file.
We can change file name by using FileUpload control's SaveAs method. SaveAs() method require to pass a parameter named filename. This parameter value is a string that specifies the full path of the location of the server on which to save the uploaded file.
To your primary question, is it good practice to rename files, the answer is a definite yes, especially if you are creating a form of File Repository where users upload files (and filenames) of their choosing, for several reason:
Cake Recipe.doc
is not a URL safe name, and can on some systems (either server or browser side) / some situations, cause inconsistencies when the name should be a urlencode
d value. As for storing the information, you would typically do this in a database, no different than the need you have already, since you need a way to refer back to the file (who uploaded, what the name is, occassionally where it is stored, the time of upload, sometimes the size). You're simply adding to that the actual stored name of the file in addition to the user's name for the file.
The OWASP recommendation isn't a bad one -- using the filename and a timestamp (not date) would be mostly unique. I take it a step further to include the microtime with the timestamp, and often some other unique bit of information, so that a duplicate upload of a small file couldn't occur in the same timeframe -- I also store the date of the upload which is additional insurance against md5 clashes, which has a higher probability in systems that store many files and for years. It is incredibly unlikely that you would generate two like md5s, using filename and microtime, on the same day. An example would be:
$filename = date('Ymd') . '_' . md5($uploaded_filename . microtime());
My 2 cents.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With