4

Possible Duplicate:
PHP: How to generate a random, unique, alphanumeric string?

I'm trying to generate unique id (alpha-numeric string). I'm using curent timestamp for that. I have two questions:

  1. Will md5(stamp1) be different from md5(stamp2) if stamp1 != stamp2.
  2. Is there a common way to generate unique string?

PS: the easiest way of cause is to take stamp as id. Still I dont want that it was easy to find out how id is generated

Community
  • 1
  • 1
Eugeny89
  • 3,797
  • 7
  • 51
  • 98

3 Answers3

11
  1. Yes, in most cases, they will be different. Chances of hash collisions are very, very low (think one in billions).

  2. The built in function uniqid() is great for this. You could even do md5(uniqid()), but be aware, this won't increase the entropy of the GUID. For increased entropy, you can call the function like this: uniqid('',TRUE);

Ayush
  • 41,754
  • 51
  • 164
  • 239
3

Using hash-functions will never be truly unique, but you can put together another string that is much closer, i.e. taking their IP address and appending the request microtime, like this:

$strUnique = sprintf('%u', ip2long($_SERVER['REMOTE_ADDR'])) . floor(microtime(true) * 1000);

For this to not be unique, two visitors would have to load the page from the same IP address at the exact same microsecond, which is more unlikely than two hashes being equal.

Flygenring
  • 3,818
  • 1
  • 32
  • 39
2

I completely agree with xbonez's answer but I would like to add that depending on what you are using it for there are a few other considerations.

  • If this is for a database id you can normally rely on the auto increment or other unique key functions of the database system to generate the id
  • if this is for file names use tempnam instead
  • you might want to use both the timestamp and a random number in the md5 since it is very conceivable that several users could hit the page on the same timestamp
hackartist
  • 5,172
  • 4
  • 33
  • 48
  • 1
    for the third issue, another workaround would be to provide a prefix to `uniqid()` such as, maybe, the user's ID, or a portion of his IP address. – Ayush Jun 14 '12 at 06:50
  • In fact, if `rand()` is seeded by timestamp, two users who visit at the same timestamp would receive the same random number. – Ayush Jun 14 '12 at 06:51