Chris Gmyr
Developer, entrepreneur, drummer, biker, dog owner, husband, and proud dad. Loves Laravel and coffee

Easy Password Handling in PHP

05/18/2011

There are many ways to handle passwords in your application, and a lot of different thoughts on it. You want to make sure your users are protected, but you also want to make sure that you are able to easily work with the data through the application. Here is how I handle passwords.

Let’s start with the basic functions:

<?php
function pass_rand($min = null, $max = null)
{
    static $seeded;

    if(!isset($seeded))
    {
        mt_srand((double)microtime()*1000000);
        $seeded = true;
    }

    if(isset($min) && isset($max))
    {
        if($min >= $max)
        {
            return $min;
        }
        else
        {
            return mt_rand($min, $max);
        }
    }
    else
    {
        return mt_rand();
    }
}

function validate_password($plain, $encrypted)
{
    $stack = explode(':', $encrypted);

    if(sizeof($stack) != 2) return false;

    if(md5($stack[1].$plain) == $stack[])
    {
        return true;
    }

    return false;
}

function encrypt_password($plain)
{
    $password = '';

    for($i=; $i<10; $i++)
    {
        $password .= pass_rand();
    }

    $salt = substr(md5($password), , 2);

    $password = md5($salt.$plain).':'.$salt;

    return $password;
}

After your user registers you will need to encrypt and save their password to your database. You can easily do this by sending their password to the encrypt_password() function:

<?php

$new_password = encrypt_password($_POST['password']);

//"password123" becomes something like "3be870c699b09266b3b86c98aeb31022:43"

When your user tries to log into your application you will need to do some initial validation to get their record from the database, but the result will look something similar to:

<?php

$sql = "SELECT `id`, `password` FROM `users` WHERE `email` = ".mysql_escape_string($_POST['email']);
$result = mysql_query($sql);
$row = mysql_fetch_row($result);
if(validate_password($_POST['password'], $row['password']))
{
    //continue with login process
}
else
{
    die('Login Failed');
}

And that’s pretty much it. Easy right?

Note: You will want to do a lot more security checking than this especially with the database interaction. This is only for demonstration ;) I recommend you use a solid framework like CodeIgniter which has a lot already built into it.