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 07:51

Something like this could work for you:

while (file_exists('/uploads/' . $filename . '.jpeg')) {
   $filename .= rand(10, 99);
}
查看更多
做个烂人
3楼-- · 2019-02-14 07:53

http://php.net/manual/en/function.uniqid.php maybe?

  • You can prefix it with the user id to avoid collisions between 2 users (in less than one millisecond).
查看更多
Explosion°爆炸
4楼-- · 2019-02-14 07:53

For good performance and uniqueness you can use approach like this:

  • files will be stored on a server with names like md5_file($file).jpg

  • the directory to store file in define from md5 file name, by stripping first two chars (first level), and second two (second level) like that:

    uploaded_files\ 30 \ c5 \ 30 c5 67139b64ee14c80cc5f5006d8081.pdf

  • create record in database with file_id, original file name, uploaded user id, and path to file on server

  • on server side create script that'll get role of download providing - it'll get file by id from db, and output its content with original filename provided by user (see php example of codeigniter download_helper ). So url to file will look like that:

    http://site.com/download.php?file=id


Pros:

  • minified collisions threat

  • good performance at file lookup (not much files in 1 directory, not much directories at the same level)

  • original file names are saved

  • you can adjust access to files by server side script (check session or cookies)

Cons:

  • Good for small filesizes, because before user can download file, server have to read this file in memory
查看更多
叼着烟拽天下
5楼-- · 2019-02-14 07:56

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.

查看更多
男人必须洒脱
6楼-- · 2019-02-14 07:58

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
查看更多
冷血范
7楼-- · 2019-02-14 07:59

try this file format:

$filename = microtime(true) . $username . '.jpg';
查看更多
登录 后发表回答