All about PHP/MySQL

Wednesday, February 27, 2008

Random string generator in PHP

In many cases, like generating a new password or setting up the custom session id, i do use the following function often in my PHP scripts for random string generation:

Function:

function random_string($length='8')
{
$ran_string = "";
$chars = array("1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "a", "A", "b", "B", "c",

"C", "d", "D", "e", "E", "f", "F", "g", "G", "h", "H", "i", "I", "j", "J", "k", "K", "l",

"L", "m", "M", "n", "N", "o", "O", "p", "P", "q", "Q", "r", "R", "s", "S", "t", "T", "u",

"U", "v", "V", "w", "W", "x", "X", "y", "Y", "z", "Z");

$count = count($chars) - 1;

srand((double)microtime() * 1000000);

for ($i = 0; $i < $length; $i++)
{
$ran_string .= $chars[rand(0, $count)];
}

return($ran_string);
}

Usage:

$new_random_string = random_string();

Happy coding :-)

4 Comments:

Post a Comment

Subscribe to Post Comments [Atom]



Links to this post:

Create a Link

<< Home