开发者

Unique, short filenames for pictures

开发者 https://www.devze.com 2022-12-27 02:01 出处:网络
What would be the best way to rename my user uploaded images to fairly short, yet unique names? uniqid() ?

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

uniqid() ?
开发者_Go百科


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.


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 ));
}


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

$imgName = md5($userEmail.microtime());


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;


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消