tags:

views:

110

answers:

5

What would be the best way to rename my user uploaded images to fairly short, yet unique names?

uniqid() ?
+3  A: 

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.

Techpriester
For large images, that will be really slow. Creating a UUID is a lot faster, even with a (pretty redundant) check for collisions
Jens Roland
True, I wouldn't recommend this for large images. But we're probably talking about fairly small files, typical for web content.
Techpriester
Note that hash algorithms are not designed to generate unique values.
Gumbo
@Gumbo: Exactly, thats the point here. A hash algorithm will give a fingerprint of the input data, so if someone uploads the same image file again in this example, it will also generate the same filename again which in the end saves storage space and also produces unique filenames for each iamge.
Techpriester
+2  A: 

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 ));
}
Jens Roland
A: 

A very simple approach is to use some unique user identifier and a timestamp,

$imgName = md5($userEmail.microtime());
elias
A: 

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;
Bryan
Bad idea, if the filename the user submitted is `../../etc/passwd` or contains \0 and stuff...
Boldewyn
A: 

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.

niggles