Generate a password in php

Generating passwords is a common task on membership sites. The following function will generate a password according to two parameters: length and strength.

function generatePassword($length=9, $strength=0) {
	$vowels = 'aeuy';
	$consonants = 'bdghjmnpqrstvz';
	if ($strength >= 1) {
		$consonants .= 'BDGHJLMNPQRSTVWXZ';
	}
	if ($strength >= 2) {
		$vowels .= "AEUY";
	}
	if ($strength >= 4) {
		$consonants .= '23456789';
	}
	if ($strength >= 8 ) {
		$vowels .= '@#$%';
	}

	$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;
}

Usage

Simply call the function as shown below. The function accept two parameters, $length, the desired length of the password, and $strength, the desired strength of the password.

echo 'Your password is '.generatePassword(10,8).'';

This will display something like: Your strong password is yQAD#ZyZ#P

2 Comments

  1. Spiro
    Posted July 1, 2010 at 10:58 pm | Permalink

    I’m using it on a client site. Good job!

  2. Eric
    Posted July 25, 2010 at 8:48 am | Permalink

    I don’t understand why you split letters into vowel and consonant ?
    IMHO, the fact that the generated password alternates vowel and consonant is a weakness…

2 Trackbacks

  1. [...] This post was mentioned on Twitter by Sully's Rants. Sully's Rants said: RT @phpsnippets: Generate a password in php : http://bit.ly/aec1Vu #php [...]

  2. By 10 life-saving PHP snippets on July 19, 2010 at 4:06 pm

    [...] } else { $password .= $vowels[(rand() % strlen($vowels))]; $alt = 1; } } return $password; }Source: http://www.phpsnippets.info/generate-a-password-in-phpCompress multiple CSS filesIf you’re using different CSS files on your site, they might take [...]

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>