I am using the php rand() function to generate coupon codes for my e commerce system. It worked fine for a while but now I am getting a lot of errors that the code is already in the system.
This is the function I use:
function generateRandomString($length) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyz';
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}
return $randomString;
}
And my codes are 32 characters long.
I did a sample of ~150 tries and noticed that more than 50% of the generated codes where laready in the system.
I have 4212 codes in the system. The odds of a 32 character random string with 36 different symbols producing a collision are basically zero, and I get 50% collisions.
When I re-seeded the random number generator in my function by calling srand();
I did not have any collisions any more.
But on the man page of php it cleary says:
Note: As of PHP 4.2.0, there is no need to seed the random number generator with srand() or mt_srand() as this is now done automatically.
I am running php version PHP 5.5.9
So my thoughts where something like that seeding is done, but only once per webserver worker, and then when the process is forked, it is not reseeded or something like that. But that would be clearly a bug in apache...
I am running php as apache modul in apache version Apache/2.4.7 (Ubuntu)
and the mpm_prefork_module
module
So do I still need to call srand()
at the top of every script dispite the manpages saying other wise, and why? Is it apaches fault or PHP's?
And yes, I am aware that I should not use this function for this purpose, and I will update it to use cryptographically secure numbers. But I think this should not happen anyway and I am still interested in what is going on!