Darcy Clarkebuilding products / experiences / communities & culture

Toggle Main Navigation

Apr 5, 2011

Randomly Generate Strings - PHP

Posted in "development"


There's going to come a time when you need to create a random string of some kind. Whether to be added as a salt for password encryption or for use as a generated password itself. Using numbers letters and special characters means a greater selection and number of combinations possible. To be exact the snippet below uses 51 different characters which has an exponential combination amount determined by the length in which you'd like the string the be. A longer length means more combinations. This allows for a seemingly infinite number of possibilities.

It's important to have a resource like this on hand and I thought I'd share mine. The function below requires one parameter, the length, and will return the randomly generated string:

function random($length) {
  $characters = "0123456789abcdefghijklmnopqrstuvwxyz!@#$%^&*()-=+_~";
  $string = "";
  for ($x = 0; $x < $length; $x++):
    $string .= $characters[mt_rand(0, strlen($characters))];
  endfor;
  return $string;
}