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.

51 Responses so far | Have Your Say!

  1. zen - Gravatar

    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.

  2. David Shaw - Gravatar

    David Shaw  |  February 20th, 2008 at 11:44 pm #

    nice one Zen.

    Great tips for the more advance users! Good Job

  3. Chris Southam - Gravatar

    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. :)

  4. averagecoder - Gravatar

    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

  5. David Shaw - Gravatar

    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!

  6. Alex Tokar - Gravatar

    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. :)

  7. David Shaw - Gravatar

    David Shaw  |  March 29th, 2008 at 6:25 pm #

    @Alex

    Thank You.

    Everyone has got to start somewhere!

    David

  8. Website Start-up Traffic | ProTycoon - Gravatar

    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‘. [...]

  9. Google PageRank Update | ProTycoon - Gravatar

    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 [...]

  10. PHP Login Script Tutorial | ProTycoon - Gravatar

    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? [...]

  11. Increase Page Views On Your Blog | ProTycoon - Gravatar

    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 [...]

  12. Wilson - Gravatar

    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

  13. ROOP - Gravatar

    ROOP  |  September 12th, 2008 at 11:02 am #

    Plz Send it

  14. ROOP - Gravatar

    ROOP  |  September 12th, 2008 at 11:09 am #

    How can we Use hash() Function for encryption of password.

  15. X_Lost - Gravatar

    X_Lost  |  November 2nd, 2008 at 2:36 am #

    Класс! Афтару респект!

  16. Sherl - Gravatar

    Sherl  |  November 3rd, 2008 at 12:38 am #

    класс)мне понра)особенно!

  17. KAMRAD - Gravatar

    KAMRAD  |  November 3rd, 2008 at 1:51 am #

    “Мало кто может похвастаться такой смекалкой, как у автора”

  18. sam_mer - Gravatar

    sam_mer  |  November 3rd, 2008 at 4:04 am #

    все может быть=))))))

  19. ok - Gravatar

    ok  |  November 3rd, 2008 at 3:27 pm #

    отлично!!! Все супер!

  20. Alarm - Gravatar

    Alarm  |  November 4th, 2008 at 1:10 am #

    Да, Именно так и было!:))

  21. mag54 - Gravatar

    mag54  |  November 4th, 2008 at 11:19 pm #

    “Отличный пост”

  22. Hrom - Gravatar

    Hrom  |  November 5th, 2008 at 4:53 am #

    Вах-вах-вах

  23. GVS - Gravatar

    GVS  |  November 5th, 2008 at 11:36 pm #

    Очень рада, что возникло желание взять этот пост в цитатник!

  24. Тимон - Gravatar

    Тимон  |  November 7th, 2008 at 3:37 am #

    прикона)

  25. Ямбуй - Gravatar

    Ямбуй  |  November 7th, 2008 at 5:47 am #

    Вах-вах-вах

  26. _Петр - Gravatar

    _Петр  |  November 7th, 2008 at 8:47 pm #

    хм…ну это памойму уже крайность…

  27. Дмитрий Г. - Gravatar

    Дмитрий Г.  |  November 8th, 2008 at 7:51 am #

    “Прямо даже не верится”

  28. завод - Gravatar

    завод  |  November 8th, 2008 at 10:08 pm #

    “Полезного много нашла для себя”

  29. Virus - Gravatar

    Virus  |  November 9th, 2008 at 4:49 am #

    “Всегда приятно читать умных людей”

  30. Жора - Gravatar

    Жора  |  November 9th, 2008 at 7:04 am #

    “Занятно”

  31. vovanfan - Gravatar

    vovanfan  |  November 11th, 2008 at 7:49 am #

    Я от них безума!

  32. Nerd - Gravatar

    Nerd  |  November 12th, 2008 at 3:39 am #

    “Хорошо пишешь”

  33. Noble Tiger - Gravatar

    Noble Tiger  |  November 12th, 2008 at 4:47 am #

    “познавательно”

  34. max - Gravatar

    max  |  November 12th, 2008 at 5:54 am #

    “Отличный пост”

  35. Bagira - Gravatar

    Bagira  |  November 14th, 2008 at 12:58 am #

    “соглашусь с автором”

  36. Bear - Gravatar

    Bear  |  November 14th, 2008 at 4:39 am #

    “здорово!”

  37. zerger - Gravatar

    zerger  |  November 14th, 2008 at 10:46 pm #

    “Занятно”

  38. риелтер - Gravatar

    риелтер  |  November 16th, 2008 at 9:44 pm #

    Ничего себе подборочка!!!!!!! Великолепно!

  39. риэлтор - Gravatar

    риэлтор  |  November 16th, 2008 at 10:55 pm #

    потрясающие идеи…нам перенять бы …великолепно.

  40. Alekhan - Gravatar

    Alekhan  |  November 17th, 2008 at 12:05 am #

    ну что тут скажешь…

  41. zaa - Gravatar

    zaa  |  November 17th, 2008 at 1:22 am #

    “Полезного много нашла для себя”

  42. Леха - Gravatar

    Леха  |  November 17th, 2008 at 2:34 am #

    Спасибо! Пригодится…..(-___________-)

  43. akvatika - Gravatar

    akvatika  |  November 17th, 2008 at 7:30 pm #

    Забавно )

  44. Alarm - Gravatar

    Alarm  |  November 17th, 2008 at 8:42 pm #

    Случайно увидел. Не ожидал.

  45. Зануда - Gravatar

    Зануда  |  November 18th, 2008 at 12:19 am #

    “Всё гуд”

  46. polomasky - Gravatar

    polomasky  |  November 18th, 2008 at 1:39 am #

    Большое спасибо! Есть ещё повод получить удовольствие… С вашего разрешения, беру.

  47. Сергей Г. - Gravatar

    Сергей Г.  |  November 18th, 2008 at 2:51 am #

    =))))))

  48. Саня - Gravatar

    Саня  |  November 18th, 2008 at 4:05 am #

    да,но это еще и не все…

  49. Scratcher - Gravatar

    Scratcher  |  November 19th, 2008 at 2:12 am #

    Спасибо за чудо))

  50. муля - Gravatar

    муля  |  November 19th, 2008 at 3:20 am #

    Спасибо за чудо))

  51. Венелин - Gravatar

    Венелин  |  November 19th, 2008 at 12:28 pm #

    “я в восторге от Вашего стиля”

Leave a Feedback

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

  Search