Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

JackD's avatar

how to generate long unique name for filename

i tried uniqid() to rename the photo to be uploaded, is there any way to generate a longer unique name?

0 likes
5 replies
khoanguyenme's avatar

very easy. add some time stamp into file and md5 hash

$unique_name = md5($filename. time());
willvincent's avatar
Level 54

passing true as the second parameter to uniqid() will get you to 23chars. md5 will be 32chars. You could also use a UUID library.

Here's some options:

uniqid()
54e6d1765a02a

uniqid('img_')
img_54e6d1765a0ec

uniqid('', true)
54e6d1765a1044.98757507

uniqid('img_', true)
img_54e6d1765a1212.51675326

md5($filename)
fe6dbefca221b544567d82f830fb9a1e

md5($filename . time())
329be60060390159f156b229f3acfe4f

md5($filename . microtime())
f261026e766a32a5f09835154483936d

If you go the md5 route, you should probably use microtime() instead of time() to salt the filename

Something like this would work too:

function NewGuid() { 
    $s = strtoupper(md5(uniqid(rand(),true))); 
    $guidText = 
        substr($s,0,8) . '-' . 
        substr($s,8,4) . '-' . 
        substr($s,12,4). '-' . 
        substr($s,16,4). '-' . 
        substr($s,20); 
    return $guidText;
}

Which outputs

5AC1949A-6257-E917-43D4-2FB1B222461D

14 likes
fahmi's avatar

Then you can add maybe a while loop just to be sure.

psnix's avatar

@eugenevdm

That function produces duplicated names.

@khoanguyenme

that wouldn't guarantee anything unique!

I think there must be a function that checks the disk for duplicated names too and generate random hashed names until it gets a unique name (however that wouldn't grantee a unique name too, specially in huge apps). some operating systems like Linux have functions that can produce a unique name. I don't know how but Laravel should utilize that or use PHP functions like tempnam

Please or to participate in this conversation.