Best method to generate unique filenames when uploading files PHP [duplicate]

≡放荡痞女 提交于 2019-11-29 16:06:35

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!