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

北慕城南 提交于 2019-11-30 11:08:55

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.

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

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.

cnizzardini

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.

EboMike

There's tempnam and tmpfile, if you want to create files, or this question.

$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

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