Create Unique Image Names

2019-02-14 07:20发布

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 suitable.

Any ideas?

标签: php filenames
13条回答
迷人小祖宗
2楼-- · 2019-02-14 08:04

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)
查看更多
登录 后发表回答