PHP uniqid

PHP uniqid

Written by Dev Dojo on Jun 15th, 2016 Views Report Post

The uniqid function in PHP is used to create random and unique sequence ids. It is often used by PHP developers to create tokens for CSRF protection or sessions. Usually, developers prefer uniqid() function over rand(), but did you know uniqid() does not always guarantee uniqueness?

The actual uniqid() function takes seconds and microseconds of the current time, and returns the same in a hexadecimal form.

Using usleep() to make uniqid() truly unique

Since uniqid() uses microseconds to determine a unique id every time, it could give the same sequence twice, if the function is called within the same microsecond.

To avoid this, usleep() can be used inside the uniqid() function. Basically, usleep() delays the entire execution by one microsecond, which makes uniqid() truly unique.

But, if there are two different processes that call uniqid() at the very same time, there would be a microsecond delay in both of them and they might end up with the same uniqid sequence.

Also, there is no usleep() function in Windows. If used, PHP just skips the usleep() function and keeps going on. As a result, there is no delay.

Parameters used in uniqid()

There are two types of parameters in uniqid():

Prefix: It is just a string which can be added on before the uniqid output. With an empty prefix, the output string is 13 characters long.

More_entropy: When this is set to TRUE, uniqid() adds appends a value to the final output, and this value can be entered by calling php_combined_lcg.

Also, with more_entropy set to true, the output string has a character count of 23.

In conclusion

With so many other options available in PHP to generate sequences, it is safe to say that uniqid() is probably one of the most efficient and customizable.

Comments (0)