Create Unique Image Names

前端 未结 15 2201
暗喜
暗喜 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条回答
  •  Happy的楠姐
    2021-01-06 08:28

    Grab the file extension from uploaded file:

    $ext = pathinfo($uploaded_filename, PATHINFO_EXTENSION);
    

    Grab the time to the second: time()

    Grab some randomness: md5(microtime())

    Convert time to base 36: base_convert (time(), 10, 36) - base 36 compresses a 10 byte string down to about 6 bytes to allow for more of the random string to be used

    Send the whole lot out as a 16 char string:

    $unique_id = substr( base_convert( time(), 10, 36 ) . md5( microtime() ), 0, 16 ) . $ext;
    

    I doubt that will ever collide - you could even not truncate it if you don't mind very long file names.

提交回复
热议问题