Ayush
Ayush

Reputation: 42450

Uniqid returning similar value every time

I'm generating a 5 letter uniqid in PHP this way:

$id = substr(uniqid(),0,5);

And every single time I call it, I get the value 5004b. Why is that happening?

If I remove the substr, the 5004b part stays constant while the remaining changes. Isn't this severely reducing the entropy of the GUID being generated?

Upvotes: 3

Views: 4673

Answers (5)

Morfat
Morfat

Reputation: 182

you could use something like substr(uniqid(rand(),1),0,7). this generates unique ids from a random seed. then again if you are saving them to a database you may need to check whether they exist before generating again. Do something like:

function idExists($id){
//query database and check if the id already exists
}
//then use this to generate
$id=null;
   do{
$id=substr(uniqid(rand(),1),0,7); 
}while(idExists($id));
//then you get your unique id here

Upvotes: 0

Axel Dörfler
Axel Dörfler

Reputation: 399

If you need a unique ID, don't use uniqid() as it only returns the an ID based on the current time. If your computer is fast enough, it will produce the same values again and again.

Enlarging the entropy (by passing "true" as the second argument) helps, but it cannot hide the fact that this function is flawed, and should not be used more than once in a script.

Upvotes: 0

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324620

uniqid() only works if you take the full value. It would make more sense to take the last five characters rather than the first:

$id = substr(uniqid(),-5);

However, after just one second you'll get repeating values. You really should just take the full uniqid().

Upvotes: 3

laurent
laurent

Reputation: 90756

To increase the entropy of the output, you can use uniqid('', true);. According to the doc, this "will add additional entropy (using the combined linear congruential generator) at the end of the return value, which increases the likelihood that the result will be unique."

Upvotes: 0

John V.
John V.

Reputation: 4670

uniqid() is based on microtime(), the beginning is going to be the same for a long time.

My suggestion is that you just increment every time or something if you need a 5 digit long uniqid.

Upvotes: 6

Related Questions