Search code examples
phpunique

PHP's uniqid function with more entropy


Question:

When using PHP's uniqid function with more entropy set the 15th character is always a period (dot) on my runs. Is the 15th character guaranteed to always be a dot?

Follow-up:

Thanks to @FuzzyTree for the answer.

I also investigated a bit further, so for those interested the php_combined_lcg() function generates a random number between 0 and 1 (such as 0.862215793). The reason there is a number before the decimal is because it is multiplied by 10 (which then becomes 8.62215793 in this example). This prevents there from always being a 0 as the 14th character.


Solution

  • Yes the 15th character is guaranteed to be a dot if more_entropy is set to true.

    From the php source for uniqid

    if (more_entropy) {
        uniqid = strpprintf(0, "%s%08x%05x%.8F", prefix, sec, usec, php_combined_lcg() * 10);
                                           ^ hard coded dot here preceeded by 14 characters
    } else {
        uniqid = strpprintf(0, "%s%08x%05x", prefix, sec, usec);
    }