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?
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
p.s.
problem can arrive if you manage to generate 2 strings in the same microsecond, rand generator may fail (and probably will).