Generating a random string

If you ever want to generate an authorization key, a random password or even a random capcha string, this simple function takes care of the grunt work for you.

It takes one parameter being the length (as in number of characters) of the string it will return. You can also edit the value of the $chars variable to define which characters you want as possible inclusions in the random string.

<?php
function get_random_string($length)
{
//The chars used to create the random string
$chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$len = strlen($chars) - 1;
$string = "";
for($i = 0; $i < $length; $i++)
{
$pos = mt_rand(0, $len);
$string .= substr($chars, $pos, 1);
}
return $string;
}
?>
Comments (0)
+ –