Generate Random Strings in PHP

May 11, 2009

I needed to generate some random strings today for password resets.  Here’s what I used:

function genRandomString($length = 10)
{
   $characters = ‘0123456789abcdefghijklmnopqrstuvwxyz’;
   $string = ”;

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

   return $string;
}

Or, recursively:

function genRandomString($i, $length = 10)
{
   $characters = ‘0123456789abcdefghijklmnopqrstuvwxyz’;
   $string = ”;

   if($i >= $length)
   {
      return '';
   }
   return $characters[mt_rand(0, strlen($characters))].genRandomString($i++, $length);
}

Stay in Touch!

Subscribe to our newsletter.

Solutions Architecture

browse through our blog articles

Blog Archive