Is generateRandomString unique?

Hello. I want to use generateRandomString to create a unique hash for each of my users. Does this function generate a unique hash each time? Or should I check the newly created hash against the database?

What’s the length I should be using in order to make sure the hash is unique?

Thank you.

As far as I know this is not guaranteed to be unique. In general - longer key = bigger chance to be unique in db.

I share Bizleys opinion…

When its "random" it means there is a very SMALL chance that the same string will be generated two times…

Otherwise the function would be called generateUniqueString() or something.

Its like throwing a bunch of dice.

The more dice you throw the smaller the chance to have the same numbers,

but it is of course possible to have the same result multiple times.

Thank you.

problem with that function is it will make base64encode which probably will decrease randomness (replaces =, etc)

i personally use custom UUID implementation based on mt_rand (which is faster than openssl_random_pseudo_bytes used in yii2). also, openssl_random_pseudo_bytes runs slower on Windows servers.

but in any case, 32 bytes are enough, it’s pow(pow( 2 , 8 ) , 32 ) chances, which equals to 1.16E+77 about total number protons in universe (according to maths), that’s not bad.

after we cut max_int as random chance to hit same 8 bytes we can be pretty sure about 5.39E+67 safe random items. (for x64 system)

check is never bad, but if your code can gracefully handle error and regenerate key - you don’t need any checks, just make sure to have forced unique index in db


problem can arrive if you manage to generate 2 strings in the same microsecond, rand generator may fail (and probably will).