-4

I'm looking to generate a UNIQUE random code.

When you use uniqid(), result is based on time, example: if user created ID yesterday at 12:12:35 and another user create a new ID today at same time, ID are identical because based on 24 hour loop time.

I'm tinking about using microtime in this way

// create random based on unix epoch
$random = round(microtime(true) * 1000);

In this way can I grant uniqueless of generated IDs?

Hid Dencum
  • 582
  • 4
  • 21
  • 2
    Can you provide an authoritative source for your claim regarding `uniqid()` generating the same string 24 hours apart? – esqew Jan 24 '19 at 21:44
  • 3
    " if user created ID yesterday at 12:12:35 and another user create a new ID today at same time, ID are identical because based on 24 hour loop time." NOOOOO its time and DATE, days changed –  Jan 24 '19 at 21:45
  • If you need uniqueness *and* unguessability, then don't base your id on the date/time. See [ramsey/uuid](https://github.com/ramsey/uuid). – Alex Howansky Jan 24 '19 at 21:46
  • _based on time_ where time is a timestamp identifying the year, month, day, hour, minute, second and microsecond. So, no there will not be a collision unless you change time or date backwards on server. – AbraCadaver Jan 24 '19 at 21:46
  • @esquev, uniqID create same codes on my server... – Hid Dencum Jan 24 '19 at 21:47
  • The result of uniqid() is not based on time but timestamp, so it is not just time but date+time. And you can increase uniqueness by setting the 2nd argument (more_entropy) to true. https://secure.php.net/manual/en/function.uniqid.php – Online Sid Jan 24 '19 at 21:50
  • please, run this on you server and see duplicated, – Hid Dencum Jan 24 '19 at 22:20
  • for($i=0;$i<20;$i++) { echo uniqid(); echo '
    '; }
    – Hid Dencum Jan 24 '19 at 22:20
  • 2
    ran you test code, no duplicates, if your server was very fast its possible the 2 calls were made in the same microsecond. This not at all what you said in your post, regarding be identical a **day** apart. –  Jan 25 '19 at 00:50

1 Answers1

0

The result of uniqid() is not based on time but timestamp, so it is not just time but date+time.

From php.net uniqid page

Returns timestamp based unique identifier as a string.

You can set the 2nd argument 'more_entropy' to true to increase it's uniqueness.

Online Sid
  • 116
  • 4