PHP: Random Password Generator

May 15, 2009

I find myself wanting random passwords all the time, and on a web project I needed to generate passwords automatically to send out to users. Here is the function I use to create random passwords automatically.

/**
 * Creates a random password
 *
 * @param Integer $length - Default: 9
 * @param Integer $strength - Default: 10
 * @return String
 **/
function generatePassword($length=9, $strength=10) {
	$vowels = 'aeuy';
	$consonants = 'bdghjmnpqrstvz';
	if ($strength & 1) {
		$consonants .= 'BDGHJLMNPQRSTVWXZ';
	}
	if ($strength & 2) {
		$vowels .= "AEUY";
	}
	if ($strength & 4) {
		$consonants .= '23456789';
	}
	if ($strength & 8 ) {
		$consonants .= '@#$%';
	}

	$password = '';
	$alt = time() % 2;
	for ($i = 0; $i < $length; $i++) {
		if ($alt == 1) {
			$password .= $consonants[(rand() % strlen($consonants))];
			$alt = 0;
		} else {
			$password .= $vowels[(rand() % strlen($vowels))];
			$alt = 1;
		}
	}
	return $password;
}