Categories
Uncategorized

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;
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.