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 :-)
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:
You could use a string instead of an array and use
$rand = rand(0, $count);
$random .= substr($chars, $rand, 1);
inside the loop to cut down on all those quotes and commas.
:)
By Nick, At March 29, 2008 at 7:23 PM
Thanx Nick.......
:-))
I was looking for such a code and its working fine.....
thanx again.................
JEFF
By Anonymous, At April 24, 2009 at 1:12 AM
Nice work. You can use array of arrays to create much simpler and customizable function, such as the following:
Generate Random Strings Using PHP
By 911... Need Code, Help, At June 26, 2009 at 12:39 AM
This is a nice article..
Its easy to understand ..
And this article is using to learn something about it..
c#, dot.net, php tutorial, Ms sql server
Thanks a lot..!
ri70
By Muhammad Azeem, At March 29, 2011 at 11:58 AM
Post a Comment
Subscribe to Post Comments [Atom]
<< Home