Is the Laravel str_random() function random enough so that I can use it for IDs?
For example:
str_random(32);
This produces a random string of length 32 made up of alphanumeric characters [a-zA-z0-9] (62 characters in total).
Which equates to 2272657884496751345355241563627544170162852933518655225856 possibilities.
However, my question is, is this going to be good enough? Or should I consider using UUIDs or another custom function.
you can use this
str_random
(Str::random()
) tries to useopenssl_random_pseudo_bytes
which is a pseudo random number generator optimized for cryptography, not uniqueness. Ifopenssl_random_pseudo_bytes
is not available, it falls back toquickRandom()
:In my opinion
quickRandom
code is not reliable for uniqueness nor cryptography.Yes, having
openssl_random_pseudo_bytes
and using 32 bytes is almost impossible to see a collision, but it's still possible. If you want to make sure your strings/numbers will be unique (99.99%), you better use a UUID function. This is what I normally use:It generates a VALID RFC 4211 COMPLIANT version 4 UUID.
Check this: http://en.wikipedia.org/wiki/UUID#Random%5FUUID%5Fprobability%5Fof%5Fduplicates
You can use this package.
For example: