Which is better? rand() or rand(100, 999)?
While going through one of our own proj开发者_开发问答ects, that other developer used rand() to give random names to image files when they are being uploaded.
My recommendation is to use rand(100, 999) for more filename with more sense. Which one you recommend? And its a low traffic website, so i am sure the risk of collision is very low.
Use tempnam
http://at2.php.net/manual/de/function.tempnam.php to savely get a filename. Provide a prefix for better identifying those files in FTP-client, explorer,..
The almost perfectly safe solution is to use whatever method you want (uniqid()
, or time()
surely being the best ones), but looking whether the file already exists first. If it already exists, use a different name, or add something like (1)
to it. Repeat until you find an available file name.
It's theoretically not entirely collision-safe either if two users upload at the exact same time and the exact same ID happens to be generated, but the risk of a collision happening here is microscopic.
If you want file names to make sense, consider using whatever real-world data you have, and adding the random ID behind it:
user500_picture1_1238273193173294323191.jpg
if you want to add information to the file name that uses spaces or umlauts, using urlencode()
is a nifty trick to get any kind of string into one that is a valid file name on all file systems.
Use uniqid function or any other way to get a really unique value. If using rand() conflicts (collisions) inevitable.
do {
$filename = '/yourpath/' . time() . '_' . rand(100,999) . '.jpg';
}
while (file_exists($filename));
精彩评论