Create unique image names

What is a good way to create a unique name for the image that my user uploads?

I do not want to have duplicates, so something like MD5 ($ filename) is not suitable.

Any ideas?

+3
source share
13 answers

as already mentioned, I believe that the best way to create a unique file name is to simply add time (). that would be like

$image_name = time()."_".$image_name;
+14
source

Take the file extension from the downloaded file:

$ext = pathinfo($uploaded_filename, PATHINFO_EXTENSION);

Take time before the second: time()

Take some randomness: md5(microtime())

Converting time to base 36: base_convert (time(), 10, 36)- base 36 compresses a 10-byte string to about 6 bytes in order to use more random string to be used

16 char:

$unique_id = substr( base_convert( time(), 10, 36 ) . md5( microtime() ), 0, 16 ) . $ext;

, - - , .

+4

( ), tempnam(), :

, 0600, .

... PHP . , , , tempnam() ; , .

+3

(, md5, sha) . ( , ). .

, :

/image/0/1/012345678/original-name.jpg

, , - .

+2

sha1_file() md5_file(). . hash_file('sha256', $filePath), .

+1

lol 633400000000000000000000000000000000000000000000000000 , md5 , .

$newfilename = md5(time().'image');
if(file_exists('./images/'.$newfilename)){
    $newfilename = md5(time().$newfilename);
}
//uploadimage
0

:

$i = 0;
while(file_exists($name . '_' . $i)){
  $i++;
}

: , . md5 .

0

, ?

    $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 ...
    }

. , .

0

:


:

  • ( 1 , )

  • you can configure access to files from the server side of the script (check session or cookies).

Minuses:

  • Good for small files, because before the user can download the file, the server must read this file in memory
0
source

try this file format:

$filename = microtime(true) . $username . '.jpg';
0
source

Something like this might work for you:

while (file_exists('/uploads/' . $filename . '.jpeg')) {
   $filename .= rand(10, 99);
}
0
source

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)
-2
source

All Articles