Create Unique Image Names

前端 未结 15 2104
暗喜
暗喜 2021-01-06 08:02

What\'s a good way to create a unique name for an image that my user is uploading?

I don\'t want to have any duplicates so something like MD5($filename) isn\'t suita

相关标签:
15条回答
  • 2021-01-06 08:18

    I'd recommend sha1_file() over md5_file(). It's less prone to collisions. You could also use hash_file('sha256', $filePath) to get even better results.

    0 讨论(0)
  • 2021-01-06 08:18

    lol there are around 63340000000000000000000000000000000000000000000000 possibility's that md5 can produce plus you could use just tobe on the safe side

    $newfilename = md5(time().'image');
    if(file_exists('./images/'.$newfilename)){
        $newfilename = md5(time().$newfilename);
    }
    //uploadimage
    
    0 讨论(0)
  • 2021-01-06 08:18

    Ready-to-use code:

    $file_ext = substr($file['name'], -4); // e.g.'.jpg', '.gif', '.png', 'jpeg' (note the missing leading point in 'jpeg')
    $new_name = sha1($file['name'] . uniqid('',true)); // this will generate a 40-character-long random name
    $new_name .= ((substr($file_ext, 0, 1) != '.') ? ".{$file_ext}" : $file_ext); //the original extension is appended (accounting for the point, see comment above)
    
    0 讨论(0)
  • 2021-01-06 08:23

    If you actually need a filename (it's not entirely clear from your question) I would use tempnam(), which:

    Creates a file with a unique filename, with access permission set to 0600, in the specified directory.

    ...and let PHP do the heavy lifting of working out uniqueness. Note that as well as returning the filename, tempnam() actually creates the file; you can just overwrite it when you drop the image file there.

    0 讨论(0)
  • 2021-01-06 08:23

    For short names:

    $i = 0;
    while(file_exists($name . '_' . $i)){
      $i++;
    }
    

    WARNING: this might fail on a multi threaded server if two user upload a image with the same name at the same time. In that case you should include the md5 of the username.

    0 讨论(0)
  • 2021-01-06 08:26

    You could take a hash (e.g., md5, sha) of the image data itself. That would help identify duplicate images too (if it was byte-for-byte, the same). But any sufficiently long string of random characters would work.

    You can always rig it up in a way that the file name looks like:

    /image/0/1/012345678/original-name.jpg
    

    That way the file name looks normal, but it's still unique.

    0 讨论(0)
提交回复
热议问题