Encrypting Passwords in PHP Login Script
Please subscribe to ProTycoon.com via the RSS Feed or Via Email.
This tutorial is a follow up to our PHP Login Script Tutorial. You will learn how to encrypt passwords to make your login script more secure.
To encrypt the passwords we will be using the md5() function. For the purpose of this tutorial we will use the same details as we used in the PHP Login Script Tutorial.
This is the data we added to the table in the Login Script Tutorial:
INSERT INTO `members` VALUES (1, 'david', 'password');
As you can see the password is not very secure, with one quick glance you know the users username and password. Now if you used the MD5() function to encrypt the password it would look something like this:
INSERT INTO `members` VALUES (1, 'david', '5f4dcc3b5aa765d61d8327deb882cf99');
As you can see that is not as easy to understand, and is alot more secure.
So how do we use the MD5() function on our Login Script?
Currently our login.php file looks like this:
<?php
$host="localhost"; // Host name
$dbusername=""; // Mysql username
$dbpassword=""; // Mysql password
$db_name=""; // Database name
$tbl="members"; // Table name
// This connects to server and then selects the members databse.
mysql_connect("$host", "$dbusername", "$dbpassword")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// Assign the username and password from the form to variables.
$username=$_POST['username'];
$password=$_POST['password'];
$sql="SELECT * FROM $tbl WHERE username='$username' and password='$password'";
$result=mysql_query($sql);
// This counts to see how many rows were found, there should be no more than 1
$count=mysql_num_rows($result);
// If result matched $username and $password, table row must be 1
if($count==1){
// Register $username, $password and send the user to the file "login_success.php"
session_start();
session_register("username");
session_register("password");
header("location:login_success.php");
}
else {
echo "Wrong Username or Password";
}
?>
To convert this code to accept MD5 encrypted passwords we need to add one extra line of code and edit the sql query.
When we get the password from the form, we added it to a variable, we now need to take this variable and encrypt the contents of it using the MD5() function, we can do that by using the code below:
$encrypted_password=md5($password);
We now need to change the sql query so that it is now searching the database for encrypted password. We need to change it from:
$sql="SELECT * FROM $tbl WHERE username='$username' and password='$password'";
to the following:
$sql="SELECT * FROM $tbl WHERE username='$username' and password='$encrypted_password'";
So there you have it you can now use encrypted passwords in your login script. The new code in full for your login.php file is:
<?php
$host="localhost"; // Host name
$dbusername=""; // Mysql username
$dbpassword=""; // Mysql password
$db_name=""; // Database name
$tbl="members"; // Table name
// This connects to server and then selects the members databse.
mysql_connect("$host", "$dbusername", "$dbpassword")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// Assign the username and password from the form to variables.
$username=$_POST['username'];
$password=$_POST['password'];
$encrypted_password=md5($password);
$sql="SELECT * FROM $tbl WHERE username='$username' and password='$encrypted_password'";
$result=mysql_query($sql);
// This counts to see how many rows were found, there should be no more than 1
$count=mysql_num_rows($result);
// If result matched $username and $password, table row must be 1
if($count==1){
// Register $username, $password and send the user to the file "login_success.php"
session_start();
session_register("username");
session_register("password");
header("location:login_success.php");
}
else {
echo "Wrong Username or Password";
}
?>
Please remember that in order for this to work you need to encrypt the users password when you add it to the database when they register.
We will be adding a Register Script Tutorial later this week, so sign up to the RSS Feed to be notified when it is published.
Any comments can be posted below.










zen | February 20th, 2008 at 10:22 pm #
the above code is happening in the server side arena except the cookie being create via sessions - so encrypting the cookie password is good and generally best practice even though the php session cookie is much better than a standard cookie.
if you are also worried about server side security then the memory footprint of $password is still there and not being overwritten by the call to the md5 function to replace $password.. which would be better imho. pedantic.. yes..
even more secure. yes.
what would enhance the security even more is two further things.
1: using SSL for the form posting and
2: using an additional layer of encryption by using javascript to scramble the form variable “password” before posting.. not entirely nessecary if your using SSL however and to some degree open to reverse engineering if no javascript md5 encryption libraries exist.
David Shaw | February 20th, 2008 at 11:44 pm #
nice one Zen.
Great tips for the more advance users! Good Job
Chris Southam | February 21st, 2008 at 9:05 am #
You really should be stripping those form posts of any SQL injection hacks - try wrapping them with mysql_real_escape_string.
averagecoder | February 21st, 2008 at 11:13 am #
Tell me if I am wrong but I see no regex filtering there. I think adding it to filter user inputs will be better but I think that is not the case here since you’re focusing on the md5.
Good post
_____________
Daniel
David Shaw | February 25th, 2008 at 1:28 pm #
The above is ok if you are a beginner.
In order to block SQL injection hacks you need to wrap the username and password inside:
mysql_real_escape_string()
So in our example you would have:
$username=mysql_real_escape_string($_POST['username']);
$password=mysql_real_escape_string($_POST['password']);
Hope that helps!
Alex Tokar | March 29th, 2008 at 11:20 am #
Nice code for beginners, really. I actually learned PHP on such examples and now I work as a professional PHP web developer.
David Shaw | March 29th, 2008 at 6:25 pm #
@Alex
Thank You.
Everyone has got to start somewhere!
David
Website Start-up Traffic | ProTycoon | March 31st, 2008 at 10:23 am #
[...] This is not a bad start, from this figure we had 584 visitors from search engines and 569 visitors from referring sites. Our most viewed post is ‘Encrypting Passwords in PHP Login Script‘. [...]
Google PageRank Update | ProTycoon | April 29th, 2008 at 11:36 pm #
[...] PR1 for the homepage, which is not a bad start. From what I can see at the moment my top PR page is Encrypting Passwords in PHP Login Script which has achieved a Google PR of [...]
PHP Login Script Tutorial | ProTycoon | April 30th, 2008 at 7:31 am #
[...] You now have a working PHP login script, feel free to use it on your web site. Why not learn how to encrypt your PHP Login Script? [...]
Increase Page Views On Your Blog | ProTycoon | April 30th, 2008 at 4:56 pm #
[...] first is to link to your related content, inside of your post, for example have a look at my Encrypting Passwords in PHP Login Script post you will notice that I have linked to my PHP Login Script Tutorial inside the post, this helps [...]
Wilson | July 31st, 2008 at 4:52 pm #
Hi.
Concerning security concerns, I do not use md5 although after reading your tutorial I will immediately implement it
A method of security that I use besides regex is as follows
function check_input($value){
// Stripslashes
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
// Quote if not a number
if (!is_numeric($value)) {
$value = "" . mysql_real_escape_string($value) . "";
}
return $value;
}
$pass = check_input($_POST['pass']);
$user = check_input($_POST['user']);
Hopefully this might help someone if deemed a usable script. MD5 encoding would come right after this script
ROOP | September 12th, 2008 at 11:02 am #
Plz Send it
ROOP | September 12th, 2008 at 11:09 am #
How can we Use hash() Function for encryption of password.