-1

I am writing a Authentication class in PHP and when i have the following function,

private function randomString($length = 50) {
    $characters = "1234567890abcdefghijklmnopqrstuvwxyz";
    $string = '';

    for ($p=0; $p < $length; $p++) { 
        $string .= $characters[mt_rand(0, strlen($characters))];
    }

    return $string;
}

i get the following error:

Notice: Uninitialized string offset: 36

I am new to creating classes so i don't know what i have done wrong here. or is there a better method of generating a random string?

  • possible duplicate of [PHP random string generator](http://stackoverflow.com/questions/4356289/php-random-string-generator) – Jigar May 14 '15 at 05:14

1 Answers1

1

Last char index is 35, you need to use strlen(...)-1:

$string .= $characters[mt_rand(0, strlen($characters) - 1)];
pavel
  • 26,538
  • 10
  • 45
  • 61