UnkwnTech UnkwnTech - 6 months ago 48
PHP Question

Generating (pseudo)random alpha-numeric strings

How can I generate a (pseudo)random alpha-numeric string, something like: 'd79jd8c' in PHP?


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.