Reputation: 31
What would be the best way to rename my user uploaded images to fairly short, yet unique names?
uniqid() ?
Upvotes: 3
Views: 856
Reputation: 1034
What is wrong with a 32 digit MD5 generated image filename? Not too long really.
If like Bryan, you're going to let them use their own filenames, make sure you strip any bad characters like: '". etc for safety sake.
Upvotes: 0
Reputation: 347
I let images upload with the original image name, for SEO purposes. Google, et al, will find users' images of Batman or Eiffel Tower if I keep the original filename intact. So I simply add mktime to the front and then save it.
$imagename = str_replace(' ','-',$imagename);
$imagename = str_replace('_','-',$imagename);
$target_path = $_SERVER['DOCUMENT_ROOT']."/uploads/".mktime()."-".$imagename;
Upvotes: 0
Reputation: 1469
A very simple approach is to use some unique user identifier and a timestamp,
$imgName = md5($userEmail.microtime());
Upvotes: 0
Reputation: 27770
You will have to accept that your file names will probably not be short, but the best practice is RFC 4122, and one of the fastest PHP implementations is this:
// Execution (1000 IDs) took 7.509 milliseconds
// Example uuid: f40bc6a1-3bce-4472-add8-bbbe500b7f72
function mimec_uuid()
{
return sprintf( '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ),
mt_rand( 0, 0x0fff ) | 0x4000,
mt_rand( 0, 0x3fff ) | 0x8000,
mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ) );
}
Personally though, I have used the following (faster and shorter) algorithm successfully for projects that didn't need to scale like Flickr:
// Execution (1000 IDs) took 5.097 milliseconds
// Example uuid: 2c2e4067d1c92109660b8deecae1be08
function xuuid()
{
return md5(microtime() . mt_rand( 0, 0xffff ));
}
Upvotes: 2
Reputation: 15832
uniqid() would work.
But you could also use md5() or sha1() to make a hash value of the actual image. That would reduce redundant files if someone uploads an image twice.
Upvotes: 3