Check password strength: PHP

Implementation

This code will validate a password on the server side. If you want to validate the password on the client side, check our Javascript. It should work with PHP4 and PHP5.

<?php
function CheckPassword($pwd) 
{
	$strength = array("Blank","Very Weak","Weak","Medium","Strong","Very Strong");
	$score = 1;

	if (strlen($pwd) < 1)
	{
		return $strength[0]; 
	}
	if (strlen($pwd) < 4)
	{
		return $strength[1]; 
	}

	if (strlen($pwd) >= 8)
	{
		$score++; 
	}
	if (strlen($pwd) >= 10)
	{
		$score++; 
	}

	if (preg_match("/[a-z]/", $pwd) && preg_match("/[A-Z]/", $pwd)) 
	{
		$score++; 
	}
	if (preg_match("/[0-9]/", $pwd)) 
	{
		$score++; 
	}
	if (preg_match("/.[!,@,#,$,%,^,&,*,?,_,~,-,£,(,)]/", $pwd)) 
	{
		$score++; 
	}

	return($strength[$score]); 
}
?php>
		

Usage

Call the method CheckPassword() passing the password to be validated, and you can then do your own validation stuff based on this result. You can also change the code to return the integer value (1 to 5, 0 if blank).

Example

<form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>">
	Password:
	<input id="TxtPassword" name="TxtPassword" type="text" />
	<span id="PasswordStrength">
		<?php if (isset($_POST["TxtPassword"]))
		echo CheckPassword($_POST["TxtPassword"]) ;?>
	</span>
	<br />
	<input type="submit" value="Validate" />
</form>
			

How does it work?

Our scripts will test passwords and return a score which represents its strength.
The score goes from 1 (Very Weak) to 5 (Very Strong), and 0 if the value is blank. It will increase by 1 point if:

Note that if the password length is less than 4, the score will be limited to "Very Weak".