Not for 'how-to' coding questions but PHP theory instead, this forum is here for those of us who wish to learn about design aspects of programming with PHP.
Properly using random is a hard task (as you've seen yourself). Do describe in more detail why you need the random value, as different "random strings" will have different properties, which you might or might not need - entropy, uniqueness, predictability, distribution.
I need to generate filename string to store images that are uploaded. Each one gets a unique random filename, just like when you upload an image to MySpace or Facebook, your image filename comes out to something like n2d8d3jd82m8fl28jfl9.jpg or l_28nf84mjf84mf8m4ifml4f.jpg
Kieran has a good idea. What if there are two files named the same thing though - that would generate the same hash but the contents would be different. 'group.jpg', 'me.jpg', etc are just some common names for images.
Maybe a hash of a string that contains both the name of the file and the time?
hash_file creates a hash from the contents of the file, not the filename. If you ever get a collision, it would be because the images are identical. filenames be damned!
Careful:
1. Two people upload the same avatar, same md5
2. One of them changed his avatar, you delete the old file (gotta check first!)
3. The second loses his avatar
You could run a "housekeeping" cron job to delete files that no longer exist in the DB, but given that storage space is so cheap (and getting cheaper) I wouldn't even bother.
This is what I'm planning on doing... I'm going to have pictures saved in sub folders, by some date type (a combination of month, week, day, or year) and then have a random 2 digit number for a sub folder on that, then a MD5 of the file, which is checked against the database to make sure it doesn't override any image already.
Does that sound like a good plan, because then at least if the same file is uploaded, it may be in a different folder (.../##/) from the random number, and then they have to be uploaded on the same day for it to even have that chance...?
sounds good, but how many files can be created using md5 cause it has to be limited to a certain number of random strings... and i'm expecting thousands of files, so i guess just do a buy year folder, so that it doesn't run into any errors down the road...
edit: nevermind i don' think i'll have 16^32 files as md5 can produce
Careful:
1. Two people upload the same avatar, same md5
2. One of them changed his avatar, you delete the old file (gotta check first!)
3. The second loses his avatar
Great catch. You could add the user id to the hash data to solve that. But personally I'd just use uniqid() and be done with it.