15

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!

Xenph Yan
  • 83,019
  • 16
  • 48
  • 55
pbh101
  • 10,203
  • 9
  • 32
  • 31

3 Answers3

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

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

USAGE: $id = uniqid(rand(), true);
Xenph Yan
  • 83,019
  • 16
  • 48
  • 55
  • wouldn't hashing it with MD5 actually make it more likely to generate collisions? – nickf Oct 08 '08 at 02:46
  • 1
    I was just about to say this. Sha1 has less collisions, but there's definitely that issue in hashing. Remember: the longer you make the unique id, and the more times you do something "random" to it, the lower the probability of collision. – Robert Elwell Oct 08 '08 at 02:47
  • Actually, I see you're point, you wanted an ID not a token value... EDITED. – Xenph Yan Oct 08 '08 at 02:49
9

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.

nico gawenda
  • 3,648
  • 3
  • 25
  • 38
Will Rhodes
  • 91
  • 1
  • 2
5

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.

Robert Elwell
  • 6,598
  • 1
  • 28
  • 32