0

Let's say I want to generate for each user in the database an alphanumeric id with the following code:

$bytes = random_bytes($length);
$identifier = bin2hex($bytes);

Should the parameter $length have a minimum value to guarantee the uniqueness of the identifiers generated for each user?

dataramix
  • 3
  • 3
  • 2
    Let the database take care of it. – Grumpy May 17 '22 at 17:19
  • 5
    You can't *guarantee* anything with a random process, you can only reduce the probability of collisions. And the answer depends on how many users you have. But the approximate number of different unique identifiers will be `256^$length`. – Barmar May 17 '22 at 17:19
  • $length, I believe it's 16, which should produce 32 characters – MisterG13 May 17 '22 at 17:19

1 Answers1

1

That depends if you need unique value or not guessable value.

Unique Identifier

If you need unique value for each user, you can use the UUID, for example Mysql has the UUID, Microsoft SQL has the Unique Idenfifier (which is basically the same), that is using the databases. Or just use the auto increment option / ID option. PHP has the method php.net uniqid Or you can try to create your own rfc 4122

Not easily guessable

Basically your question. You can use also the openssl random function or some other variations of pseudo-random number generator. There is no way to my knowledge you can guarantee the uniquenes of the values generated. You can however try to lower the posibility of such colision by setting the number of combinations reasonably high and hope for the best.

Third option

There is Unique non-repeating random numbers thread about how to generate them, but i do not believe that they are more viable for your use than your question with a do-while cycle checking the validity.

Alesseon
  • 51
  • 1
  • 4