问题
This question already has an answer here:
- Unique and temporary file names in PHP? 9 answers
Can any one suggest the best practice to generate unique file names for file uploads to avoid duplicate Entries?
Thanks In Advance.
回答1:
I usually either create a UID using uniqid() function for the filename or create a folder with the name of the username who is uploading the file and leave the original filename. The disadvantage of the first one is that you will have to save the original filename somewhere to show to the user.
回答2:
This function may help:
http://php.net/manual/en/function.uniqid.php
You may also consider looking into using a hash of the files contents such as:
http://php.net/manual/en/function.sha1-file.php
回答3:
You could use the unix timestamp of when the file was uploaded. If you expect several uploads to occur simultaneously, you could append a unique user ID or part of the original filename.
回答4:
Something like this:
$filename = md5(date('Y-m-d H:i:s:u'));
Since MD5 hashes are not guaranteed to be unique, it's a good idea to check for collisions using file_exists($filename). In that case, rerun the above.
回答5:
There's tempnam and tmpfile, if you want to create files, or this question.
回答6:
$username.$timestamp.$randomNumber
or you could hash this if you don't want people to know details of when it was uploaded and by whom
来源:https://stackoverflow.com/questions/4371941/best-method-to-generate-unique-filenames-when-uploading-files-php