Generating a unique ID in PHP

pbh101 picture pbh101 · Oct 8, 2008 · Viewed 14.6k times · Source

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!

Answer

Xenph Yan picture Xenph Yan · Oct 8, 2008
string uniqid ([ string $prefix [, bool $more_entropy ]] )

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

USAGE: $id = uniqid(rand(), true);