Posts Tagged ‘string’

php random string generator function

Wednesday, July 16th, 2008

Many people need a random string for things such as salts, activation keys and new passwords. Here’s a simple but versatile function to return a random string

function rand_text(   $min = 10,
                      $max = 20,
                      $randtext = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890' )
{
    if($min < 1) $min=1;
    $varlen = rand($min,$max);
    $randtextlen = strlen($randtext);
    $text = '';

    for($i=0; $i < $varlen; $i++)
    {
        $text .= substr($randtext, rand(1, $randtextlen), 1);
    }
    return $text;
}

To call this function, you can simply use rand_text() which will return a random alphanumeric string between 10 and 20 characters long. You can also specify a min and max length, and can also specify the string of characters that can be used in the random string. For example

echo rand_text(5,8,'abcdef0123456789');

will output a random hex value between 5 and 8 characters in length such as 2fe4e1