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:38

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.

查看更多
倾城 Initia
3楼-- · 2019-02-14 07:44

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.

查看更多
Luminary・发光体
4楼-- · 2019-02-14 07:47

as it was mentioned, i think that best way to create unique file name is to simply add time(). that would be like

$image_name = time()."_".$image_name;
查看更多
萌系小妹纸
5楼-- · 2019-02-14 07:47

How big is the probablity of two users uploading image with same name on same microsecond ?

try

    $currTime = microtime(true);
    $finalFileName = cleanTheInput($fileName)."_".$currTime;

// you can also append a _.rand(0,1000) in the end to have more foolproof name collision

    function cleanTheInput($input)
    {
     // do some formatting here ...
    }

This would also help you in tracking the upload time of the file for analysis. or may be sort the files,manage the files.

查看更多
做个烂人
6楼-- · 2019-02-14 07:49

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.

查看更多
欢心
7楼-- · 2019-02-14 07:50

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.

查看更多
登录 后发表回答