Generate Password

Description: Generates a random password with specified length and uses uppercase/lowercase letters and numbers.
Tested Platform: PHP 5
Language: PHP
// Generates a password of specified length, 8 by default
// Expects: length of password is greater than 0
// Returns: Random password of specified length based on numbers and letters

function generatePassword($length = 8) {
     $pass = '';
		
     for ($i = 0; $i < $length; $i++) {
          switch (rand(0,2)) {
               case 0: $pass .= rand(0,9); break;
               case 1: $pass .= chr(rand(65, 90)); break;
               default: $pass .= chr(rand(97,122));
          }
     }
		
     return $pass;
}

Submitted: December 24, 2012

Return to the snippets listing