© 2024 fjorge. All rights reserved.
Generate Random Strings in PHP
I needed to generate some random strings today for password resets. Here's what I used:
function genRandomString($length = 10)
{
$characters = ‘0123456789abcdefghijklmnopqrstuvwxyz’;
$string = ”;
for ($p = 0; $p < $length; $p++)
{
$string .= $characters[mt_rand(0, strlen($characters))];
}
return $string;
}
Or, recursively:
function genRandomString($i, $length = 10)
{
$characters = ‘0123456789abcdefghijklmnopqrstuvwxyz’;
$string = ”;
if($i >= $length)
{
return '';
}
return $characters[mt_rand(0, strlen($characters))].genRandomString($i++, $length);
}