Can any one suggest the best practice to generate unique file names for file uploads to avoid duplicate Entries?
Thanks In Advance.
Can any one suggest the best practice to generate unique file names for file uploads to avoid duplicate Entries?
Thanks In Advance.
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:
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.
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.
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