4

I'm looping through an array and for each record generating unique identifier with uniqid:

foreach($emailsByCampaign as $campaign => $emails) {
    $campaignHex = $this->strToHex($campaign);
    $values = "(";
    for ($i=0; $i<sizeof($emails);$i++) {
        $values .= $analyticsDbInstance->escape($emails[$i]) . ",'" . uniqid(true) . "'), (";
    }
}

Official documentation states that uniqid generates id based on microseconds. What is the likely that two cycles of the loop will pass in less than two seconds which will lead to not unique ids?

Max Koretskyi
  • 101,079
  • 60
  • 333
  • 488

1 Answers1

4

uniqid() generates a value based on the number of microseconds since the start of the Unix epoch - 1st January 1970. On a single machine every ID will be unique. It is possible (but unlikely) that two separate machines might generate the same uniqid() in which case the prefix and entropy parameters can be used to avoid this.

There are a number of implementations of UUID (or GUID) in PHP, but these generally generate V4 UUIDs, which aren't guaranteed to be unique (but the probability of a collision is vanishingly small)

If you need to generate something more secure you can use openssl-random-pseudo-bytes()

  • _On a single machine every ID will be unique_ regardless of the time it takes to go one loop? I'll be using one machine only so if the uniqueness is guaranteed, `unique` is enough. – Max Koretskyi Jan 29 '14 at 12:19