Below is the code for random string generation, it is working but there is some problem here which I at the moment cant figure out what happens here is that it always returns me value of length 1 ,I am expecting a random string of length 10. Also I am passing 10 as length. Kindly guide me what am I doing wrong here.
<?php
function random_string($length) {
$len = $length;
$base = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz123456789";
$max = strlen($base) - 1;
$activatecode = '';
mt_srand((double) microtime() * 1000000);
while (strlen($activatecode) < $len + 1) {
$activatecode.=$base{mt_rand(0, $max)};
return $activatecode;
}
}
?>
5 Answers 5
you return from within the while, causing the while-loop to only be run once and returning the result at that point (which is only 1 character)
Move your return-line 1 down (out of the while-loop) and it should work.
1 Comment
Your return statement is inside of the while loop making it to exit the function immediately, move it to the end of the function.
Some additional remarks:
- No need for
mt_srand((double) microtime() * 1000000);nowadays. - Don't use
strlen, you don't need it. {}substring syntax is outdated.
Example:
<?php
function random_string($length)
{
$length = (int) $length;
if ($length < 1) return '';
$base = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz123456789";
$max = strlen($base) - 1;
$string = '';
while ($len--)
{
$string .= $base[mt_rand(0, $max)];
}
return $string;
}
?>
I suggest you add a maximum length as well, just in case.
Comments
Seem to work fie for me.
Fix you code up a bit:
function random_string($length) {
$len = $length;
$base = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz123456789";
$max = strlen($base) - 1;
$activatecode = '';
mt_srand((double) microtime() * 1000000);
while (strlen($activatecode) < $len + 1) {
$activatecode.=$base[mt_rand(0, $max)];
}
return $activatecode;
}
Comments
Your return statement is inside of the while loop.
Move it outside to be after the end of the while loop.
Comments
Just curious, whats the point of multiplying microtime() * 1000000?
each time microtime() is called it will produce a different seed!