How to Create a Random Password for Users

If you’re working on a user-management system, you may find it useful to be able to create a random password for users.

Some systems generate these initially and have the user log in to set a permanent password. You might also have a “Reset” button, where the script generates a random password and e-mails it to the user.

This quick tutorial will show you how to create an 8 character random password containing a mix of letters and numbers. Or, if you’re impatient, jump straight to the function’s source code

There are plenty of ways to do this. The simplest method would be to take a random number, generate an md5 hash, and then use the first 8 characters as the password.

$password = md5( time() );
$password = substr($password, 0, 8);

But this doesn’t guarantee you an even mix of upper case letters, lower case letters, and numbers. To do that, we’ll need to use a few simple php functions and build a short script.

Build a Loop to Create Eight Characters

We’ll start our script by creating a blank string, looping eight times, and entering a character in the string each time.

$password = '';
for ($x = 0; $x < 8; $x++) {
   $password .= 'a';
}

This creates a blank string ($password) and iterates a loop eight times. At this point, the loop simply enters the letter ‘a’ into $password – so you end output should be ‘aaaaaaaa.’

Generate Random Characters

Now we need to generate random characters to go inside of the string. To do this, we can make use of the rand() and chr() functions. Replace the loop contents with this line.

$password = chr( rand(60, 95) );

chr() takes an integer and returns the ASCII equivalent of that number. In this case, we’re using rand() to get a number between 60 and 95 – so we should get an uppercase letter in return. Our random password should now contain eight random upper-case letters.

Randomly Enter Uppercase, Lowercase, and Numbers

To make the random password more secure, we should randomize whether the new character is a number, an upper-case letter, or a lower-case letter. We can execute a simple “switch” statement to randomly choose which type of character to enter.

Replace the loop contents with this new snippet.

switch ( rand(1, 3) ) {
 
   //  Add a random digit, 0-9
   case 1:
   $password .= rand(0, 9);
   break;
 
   //  Add a random upper-case letter
   case 2:
   $password .= chr( rand(65, 90) );
   break;
 
   //  Add a random lower-case letter
   case 3:
   $password  .= chr( rand(97, 122) );
   break;
}

We’re using rand(1, 3) to randomly choose which case to execute. Each case then enters a different type of character in the string. The first case simply returns a random digit. The second and third cases use chr() and rand() to return a random character.

At this point, the script should give you an eight-character password with a random mix of uppercase letters, lowercase letters, and numbers. Now you can e-mail the password to the user, take a hash of the password, and store it in the database.

For reference, here’s the entire script placed in a function.

function randPassword() {
   $password = '';
 
   for ($x = 1; $x <= 8; $x++) {
      switch ( rand(1, 3) ) {
 
      //  Add a random digit, 0-9
      case 1:
      $password .= rand(0, 9);
      break;
 
      //  Add a random upper-case letter
      case 2:
      $password .= chr( rand(65, 90) );
      break;
 
      //  Add a random lower-case letter
      case 3:
      $password  .= chr( rand(97, 122) );
      break;
      }
   }
 
   return $password;
}
Bookmark and Share:
  • Digg
  • Furl
  • del.icio.us
  • StumbleUpon
  • MisterWong
  • DZone
  • Technorati

Tags: , , , , , , ,

9 Comments to “How to Create a Random Password for Users”

  1. Sue Massey said this on

    I found your site on google blog search and read a few of your other posts. Keep up the good work. Just added your RSS feed to my feed reader. Look forward to reading more from you.

    - Sue.

  2. ross said this on

    this is cool… thanks…

  3. Harish Kumar said this on

    LOvely tutorial keep up the good work.. keep posting such a beautiful codes. i have bookmarked this page..
    and i suggest everyone(All PHP developers) to visit this page and read the articles posted here!!!

  4. Lauren said this on

    Great explinations i look forward to reading more!

  5. HoaiDuc said this on

    I had used this generate code but please I can ask a problem in random code contains special charaters as ^,/,`,…. Is it nescessary ?

  6. Walkere said this on

    Not sure I understand what your asking. If you use the code above, you won’t ever get those special characters.

    The character ranges specified in the example (0-9, 65-90, 97-122) only includes 0-9, a-z, A-Z.

    If you want to include a bunch of random characters, you could add a fourth case for special characters. Within that fourth case, generate a random number and use that to create a special character based on it’s ASCII code.

    However, most passwords exclude special characters, other than maybe underscores.

  7. butzi said this on

    To see this expamle in action, you could visit my site under the following address:
    http://www.functions-online.com/en/generate-password.html

    The function i wrote, is something more advanced and has more options to choose.

  8. kazet said this on

    i prefer this my own
    $randname = ”;
    $chr = ‘abcdefghijklmnopqrstuwvxyzABCDEFGHIJKLMNOPQGRSTUWVXYZ123456789′;
    $num = rand(1, strlen($chr));
    while(strlen($randname) <= 10) {$randname .= $chr[$num];}

  9. How to Create a Random Password for Users - Tutorial Collection said this on

    [...] View Tutorial No Comment var addthis_pub=”izwan00″; BOOKMARK This entry was posted on Friday, June 5th, 2009 at 8:02 am and is filed under Php Tutorials. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site. [...]

Leave a Reply