Create Unique Image Names

前端 未结 15 2116
暗喜
暗喜 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

    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)
    

提交回复
热议问题