Generating (pseudo)random alpha-numeric strings

First make a string with all your possible characters:

 $characters="abcdefghijklmnopqrstuvwxyz0123456789";

You could also use range() to do this more quickly.

Then, in a loop, choose a random number and use it as the index to the $characters string to get a random character, and append it to your string:

 $string = '';
 $max = strlen($characters) - 1;
 for ($i = 0; $i < $random_string_length; $i++) {
      $string .= $characters[mt_rand(0, $max)];
 }

$random_string_length is the length of the random string.

Leave a Comment