Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating a unique ID in PHP

I'm trying to generate a unique ID in php in order to store user-uploaded content on a FS without conflicts. I'm using php, and at the moment this little snippet is responsible for generating the UID:

$id = tempnam (".", "");
unlink($id);
$id = substr($id, 2);

This code is hideous: it creates a temporary file on the FS and deletes it, retaining only the relevant unique part of the generated string.

Is there any better way to do this, most preferably without any external dependencies?

Thanks much!

like image 329
pbh101 Avatar asked Oct 08 '08 02:10

pbh101


People also ask

How to generate unique key in PHP?

The uniqid() function generates a unique ID based on the microtime (the current time in microseconds). Note: The generated ID from this function does not guarantee uniqueness of the return value! To generate an extremely difficult to predict ID, use the md5() function.

What is Uniqid PHP?

The uniqid() function in PHP is an inbuilt function which is used to generate a unique ID based on the current time in microseconds (micro time). The ID generated from the uniqid() function is not optimal since it is based on the system time and is not cryptographically secured.

Is PHP timestamp unique?

uniqid() in PHP generates a unique ID based on the current timestamp in microseconds.


3 Answers

string uniqid ([ string $prefix [, bool $more_entropy ]] )

Gets a prefixed unique identifier based on the current time in microseconds.

USAGE: $id = uniqid(rand(), true);
like image 162
Xenph Yan Avatar answered Sep 21 '22 04:09

Xenph Yan


Since both uniqid() and rand() are functions based on the current time, rand() adds almost no entropy, since the time will change only a tiny amount between the respective calls.

As long as you use the more_entropy option, you should never have a collision within a single server. If you use clustering, be sure to include a prefix that differs between servers.

like image 34
Will Rhodes Avatar answered Sep 24 '22 04:09

Will Rhodes


uniqid() is what you're looking for in most practical situations.

You can make it even more "uniq" by adding a large random number after it.

like image 45
Robert Elwell Avatar answered Sep 20 '22 04:09

Robert Elwell