Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Unique Image Names

Tags:

php

filenames

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?

like image 262
edwinNosh Avatar asked Mar 18 '11 07:03

edwinNosh


3 Answers

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;
like image 146
user1486707 Avatar answered Oct 27 '22 14:10

user1486707


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.

like image 8
andy Avatar answered Oct 27 '22 14:10

andy


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.

like image 4
Matt Gibson Avatar answered Oct 27 '22 13:10

Matt Gibson