Correct way to make sure all files have unique names?
I have members of my site uploading image files.
What are the top/best pick ways to make sure there is no file with the same name uploaded?
My idea was to incorporate the member ID somewhere in the f开发者_JAVA百科ilename and md5 encrypt it. Any other ideas?
If you're not worried about the readability/length of the filename, then using uniqid to generate the "base" of the filename prior to adding the relevant extension would probably be the simplest solution.
(If you're likely to be generating lots of filenames in a sub-microsecond period, enable the more_entropy
option.)
As a bit of a kludge you can incorporate the current epoch time. A better solution would be to have a Singleton class which issues identifier numbers from an incremented private data member.
Using uniqid()
as shown by @Middaparka would be a reasonably safe way, and the best one if you don't care about what the file name looks like. It is extremely unlikely that the same user manages to make two identical requests with the same file in the same microsecond.
If you want to keep the original file names (which brings - solvable but important - issues with non-ASCII characters), an ever increasing counter would be the safest thing.
1_IMG0085.JPG
2_Lilies_and_pond.JPG
3_Awesome_Party_Pic.JPG
there is no chance of collisions this way, but such a counter is not entirely trivial to implement if you want to be race condition safe.
Are you creating a database record when a user uploads an image? In that case, you could use the ID from the newly created record as the counter variable.
just rename the image to a GUID + the image extension
精彩评论