phpstringuniquemicrotime

create unique string in php with base_convert and limited length


I need a string with max 6 length and mixed of number and alphabet. I checked:

How can I make short random unique keys, like YouTube video IDs, in PHP?

and

PHP generate a unique string

that was very useful but they make string with length 10 - 12. my question is that output of this code is always unique or not?

base_convert(microtime(false), 6, 36);

or

base_convert(uniqid('test',true), 6, 36);

Note: I convert from base 6 but the input is obviously not going to be base 6. I do it because if convert from 10 to 36 it generate 10-12 length.


Solution

  • Short Answer: No, but if you are doing something tiny like a personal website, or a internal only tool used by very few people it will be OK.

    Long answer: Definitely not if you are trying to do something secure, or using multiple servers that share database. Attackers can figure out exactly how long it takes for their request to reach your server and bombard it with their requests until your server generates duplicate IDs if you rely on microtime. uniqid function is not guaranteed to return uniq value(straight from php manual), and will definitely generate duplicate IDs if you are updating your time using NTP and it adjusts your time to 5 seconds ago.