Random String or Password Generator

The following function returns a random string of the length passed to the function, with a default length of 8 if none is passed.

If you look at the $chars string that supplied the character list for generating the string, you'll see that I've eliminated easily confused characters such as the zero and upper case "O", and the number "1" and lower case "l". This reduces support calls when users have to type the string in manually, as in when it is used as a temporary password.

I use this for generating temporary passwords when people are resetting lost passwords on a website and in other uses where I need a random string.

Where security is a significant concern, you may want to research random string generation more thoroughly.

function GeneratePassword($length = 8) {
  $chars = '2346789abcdefghjkmnprtuvwxyz';
  for ($p = 0; $p < $length; $p++) {
    $result .= $chars[mt_rand(0, 27)];
  return $result;

About Editor