PHP and AJAX - Make a Password Strength Bar that Updates in Real-time
This tutorial will show you how to make a very simple feature which will help your users make more secure passwords, in registration forms. After the user types their password, this script will make a request to a PHP page, which will check the password for lowercase letters, uppercase letters, numbers and symbols. Without reloading the page, a bar displaying the strength of the password will be shown to the user.

This tutorial is not going to go through making a registration system because there are already plenty of tutorials on how to make one, this tutorial will just show how you can add a password strength meter in an existing registration system.

The first script will just be HTML, CSS and Javascript. Nothing fancy, just a field to input the password and the meter below it. Save this file as form.php.

<script type="text/javascript">
function toggle_pass(passid) {
    if (window.XMLHttpRequest) {
        http = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        http = new ActiveXObject("Microsoft.XMLHTTP");
    }
    handle = document.getElementById(passid);
    var url = 'ajax.php?';
    if(handle.value.length > 0) {
        var fullurl = url + 'do=check_password_strength&pass=' + encodeURIComponent(handle.value);
        http.open("GET", fullurl, true);
        http.send(null);
        http.onreadystatechange = statechange_password;
    }else{
        document.getElementById('password_strength').innerHTML = '';
    }
}

function statechange_password() {
    if (http.readyState == 4) {
        var xmlObj = http.responseXML;
        var html = xmlObj.getElementsByTagName('result').item(0).firstChild.data;
        document.getElementById('password_strength').innerHTML = html;
    }
}
</script>

<style type="text/css">
    input {
        border: 1px solid #000000;
        padding: 5px;    
    }
    #password_strength {
        width: 250px;
        background: #cccccc;
    }
    #password_bar {
        font-size: 11px;
        background: #7FFF00;    
        border: 1px solid #cccccc;
        padding: 5px;
    }
</style>

<input id="pass" type="password" name="password" onchange="toggle_pass('pass')" /><br /><br />
<strong>Password Strength</strong>:<br />
<div id="password_strength"> </div>




This tutorial is assuming the reader knows atleast basic HTML and CSS, so I am not going to explain that, but I will explain the basics of what the Javascript is doing.

if (window.XMLHttpRequest) { - This is checking if the browser is IE or not. If it returns true it is not IE and uses the handle for non-IE browsers. If it is IE then it will use a different function to create the handle.
handle = document.getElementById(passid); - This creates a handle for the password form, so we can retrieve the value.
var fullurl = url + 'do=check_password_strength&pass=' + encodeURIComponent(handle.value); - This assembles the query string which we will use to make the request, although the "do=check_password_strength" is unnecessary in this case because this tutorial only has one type of request being made the ajax.php, people often add more ajax features to their site, so instead of making a new file for each one you can just make put "do=some_other_action" in the URL to differentiate other actions. This will be more clear later on when we make ajax.php.
http.open("GET", fullurl, true); - This will open the URL and retrieve the result.
http.onreadystatechange = statechange_password; - This will set the function to handle the result.
var html = xmlObj.getElementsByTagName('result').item(0).firstChild.data; - The result is in the form of an XML file, so this will get the tag with the name "result" and get the data in it, e.g. <result>This is the data in it</result>.
document.getElementById('password_strength').innerHTML = html; - This will output the result on the page.

Now onto some actual PHP, save this file as ajax.php.

<?php
$do 
$_GET['do'];
switch(
$do) {
    case 
'check_password_strength':
        
$password $_GET['pass'];
        
$strength 0;
        
// letters (lowercase)
        
if(preg_match("/([a-z]+)/"$password)) {
            
$strength++;
        }
        
// letters (uppercase)
        
if(preg_match("/([A-Z]+)/"$password)) {
            
$strength++;
        }
        
// numbers
        
if(preg_match("/([0-9]+)/"$password)) {
            
$strength++;
        }
        
// non word characters
        
if(preg_match("/(W+)/"$password)) {
            
$strength++;
        }
        
header('Content-Type: text/xml');
        
header('Pragma: no-cache');
        echo 
'<?xml version="1.0" encoding="UTF-8"?>';
        echo 
'<result><![CDATA[';
        switch(
$strength) {
            case 
1:

                echo 
'<div style="width: 25%" id="password_bar">Very Weak</div>';
            break;
            case 
2:
                echo 
'<div style="width: 50%" id="password_bar">Weak</div>';
            break;
            case 
3:
                echo 
'<div style="width: 75%" id="password_bar">Strong</div>';
            break;
            case 
4:
                echo 
'<div style="width: 100%" id="password_bar">Very Strong</div>';
            break;
        }
        echo 
']]></result>';
    break;
    default:
        echo 
'Error, invalid action';
    break;
}
?>


Code Breakdown:

switch($do) { - As I explained before, this is not needed for this tutorial but it is there if you are going to use other AJAX features on your site, so you can keep it all in one file.
if(preg_match("/([a-z]+)/", $password)) { - This will check the password for any lowercase letters. The other preg_match calls you see in the next few lines will check uppercase letters, numbers, and non-word characters, respectively.
$strength++; - I am sure everyone who knows basic PHP will know that this will just add 1 to the variable $strength. This code will just add 1 to each $strength for each level it meets (e.g. lowercase letters, uppercase letters etc.).
header('Content-Type: text/xml'); - This will change the header type so it will expect XML output.
echo '<result><![CDATA['; - This will make a XML element called result, which as you may have guessed, will hold the result. The <![CDATA[ is there so the data you put between it doesn't mess up the XML layout. (if you didn't have it there, the <div> tag would be treated as an XML element, instead of the result)
echo '<div style="width: 25%" id="password_bar">Very Weak</div>'; - This is the result which we are going to show, since there is only 4 levels the password can be, it has been set to be either 25%, 50%, 75% or 100%.

Here is what your result should look like: (I entered the password "abc123")



Hopefully you are a bit more creative than me when it comes to the design, but I tried to keep it simple for the sake of the tutorial just getting across the method of doing this.


Pages (1) 1
Tutorial Statistics
Date Added: 20-04-2008
Votes: 5
Rating: 8
Views: 12316

Author: scott

Main Category:
PHP
Sub-Category:
Security


Rate:
1 2 3 4 5