Unique short names for images

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

uniqid() ?
+3
source share
5 answers

uniqid () will work.

But you can also use md5 () or sha1 () to create a hash value of the actual image. This will reduce redundant files if someone uploads the image twice.

+3
source

You will have to agree that your file names will probably not be short, but RFC 4122 is the best practice, 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, however, I used the following (faster and shorter) algorithm for projects that do not need to scale like Flickr:

// Execution (1000 IDs) took 5.097 milliseconds
// Example uuid: 2c2e4067d1c92109660b8deecae1be08
function xuuid()
{
    return md5(microtime() . mt_rand( 0, 0xffff ));
}
+2

- ,

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

I allow the upload of images with the original image name for SEO purposes. Google et al. Find images of Batman or Eiffel Tower users if I keep the original file name unchanged. So I just add mktime to the beginning and then save it.

$imagename = str_replace(' ','-',$imagename);
$imagename = str_replace('_','-',$imagename);
$target_path = $_SERVER['DOCUMENT_ROOT']."/uploads/".mktime()."-".$imagename;
0
source

What is wrong with the 32-digit MD5 image file name? Not too long.

If you like Brian, you allow them to use their own file names, make sure you delete any bad characters: "", etc. for safety.

0
source

Source: https://habr.com/ru/post/1741649/


All Articles