Monthly Archives: January 2014

Generating random strings in PHP

When looking to generate random strings using PHP, there are a few sources of information that are available, but with a lot of conflicting advice. I have just had a need to implement this functionality and thought I would document what I did for the benefit of others.

function generate_random_string($length)
{
  $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  $output = "";

  for ($i = 0; $i < $length; $i++) {
     $pos = mt_rand(0, strlen($chars) - 1); 
     $output .= $chars[$pos];
  }

  return $output;
}