How to keep your passwords safe in PHP using md5 encryption

PHP offers the md5 function which calculates the MD5 hash of a string using the MD5 Message-Digest Algorithm. This algorithm takes a string and generates a 128-bit fingerprint of the input string. MD5 is a one-way encryption which means that you cannot decipher the fingerprint to get the original string. Yet another feature of MD5 is that the algorithm will always generate the same fingerprint for a given string. This tutorial demonstrates how to use PHP md5 function to encrypt the passwords in your website.

To keep things nice and simple we will create two HTML pages :

  1. user_reg.html (User registration page)
  2. user_login.html (Login page)

and two PHP scripts:

  1. Register.php (Registration script)
  2. Login.php (Login script)

User Registration page

This page is used by New users to register their username and passwords. It has three input fields for the user to enter the username, password and to confirm the password entered. The user fills out the form and press the Register button. A javascript function validateForm() performs some basic input validation. The form data is then send for processing to register.php script.

user_reg.html

<!DOCTYPE html>
<html>
<head>
<title>User Registration</title>
</head>
<body>
<script>
function validateForm() {
     var n = document.forms["regform"]["name"].value;
     var p1 = document.forms["regform"]["passwd"].value;
     var p2 = document.forms["regform"]["passwdcfm"].value;
     if (n == "" || p1 == "" || p2 == "" ) {
         alert("Please input all fields.");
         return false;
     }
     else if (p1 != p2) {
      	alert("Password fields does not match.");
        return false;
     }
 }
</script>

<form name="regform" action="register.php" method="post" onsubmit="return validateForm()"  >
<h1>User Registration Form</h1>
<table>
  <tr>
  	<td><label for="name">Username</label></td>
  	<td><input name="uname" id="name"></td>
  </tr>
  <tr>
  	<td><label for="passwd">Password</label></td>
  	<td><input type="password" name="passwd" id="passwd"></td>
  </tr>
  <tr>
  	<td><label for="passwdcfm">Confirm Password</label></td>
  	<td><input type="password" name="passwdcfm" id="passwdcfm"></td>
  </tr>
  <tr>
  	<td colspan="2"><input type="submit" value="Register" name="register"></td>
  </tr>
 </table>
</form>
</body>
</html>

Registration Script

The registration PHP script - register.php, checks if the username already exist in the passwd.txt, which is the text file that stores all usernames and passwords. If the username does not exist then it is added to the file along with the md5 hash of the password, otherwise an error message is displayed. The passwd.txt file contains one entry per line for each useraname and password combination. A semicolon(:) is used to seperate the username from the password as below

passwd.txt

username:password

register.php

<?php

//Check if username already exists in the password file
foreach(file('passwd.txt') as $line) {
   // Skip empty lines
    if(empty($line)) continue;

    // Extract usernames and password
    $lineArray = explode(':', $line);
    $username = rtrim($lineArray[0]);

	if ($_POST["uname"] == $username){
    	echo "This user already exist.";
    	return;
    }
}

// Add new username and md5 fingerprint of password to passwd.txt file
$line = $_POST["uname"] . ":" . md5($_POST["passwd"]) . "\n";
file_put_contents('passwd.txt', $line, FILE_APPEND);
echo "Registration completed successfully.";

?>

Login Page

Login page is used by registered users to login to the website. The validateForm() Javascript performs some basic validation of form data which is then submitted to the PHP script - login.php for processing.

user_login.html

<!DOCTYPE html>
<html>
<head>
<title>Login</title>
</head>
<body>
<script>
function validateForm() {
     var n = document.forms["logform"]["name"].value;
     var p1 = document.forms["logform"]["passwd"].value;
         if (n == "" || p1 == "" ) {
         alert("Please input all fields.");
         return false;
     }

 }
</script>

<form name="logform" action="login.php" method="post" onsubmit="return validateForm()"  >
<h1>Login</h1>
<table>
  <tr>
  	<td><label for="name">Username</label></td>
  	<td><input name="uname" id="name"></td>
  </tr>
  <tr>
  	<td><label for="passwd">Password</label></td>
  	<td><input type="password" name="passwd" id="passwd"></td>
  </tr>
  <tr>
  	<td colspan="2"><input type="submit" value="Login" name="Login"></td>
  </tr>
 </table>
</form>
</body>
</html>

Login Script

The Login PHP script - login.php reads the passwd.txt file line by line and checks if a match can be found for username and md5 hash of the password that was entered by the user.

login.php


<?php

foreach(file('passwd.txt') as $line) {
    // Skip empty lines
    if(empty($line)) continue;

    // Extract usernames and password
    $lineArray = explode(':', $line);
    $username = rtrim($lineArray[0]);
    $password = rtrim($lineArray[1]);

	// Check if usernames and passwords match.
	// Here we again take the md5 hash of the password entered.
   	if ($_POST["uname"] == $username && md5($_POST["passwd"]) == $password){
    	echo "Username and Password match. Logged in successfully :)";
    	return;
    }
}
// show message if no match is found
echo "Username/Password mismatch. Login Failed :(";

?>

Note: MD5 algorithm is not 100% secure and can be cracked with brute force attacks particularly with short input strings. However with longer passwords it is the best encrytion method for keeping your passwords secure.


Post a comment

Name

Your Comment

Email (We dont publish it)

Comments

Fredrik Ellertz | March 9, 2016 10:40 AM |

Never use md5! A person can look up your md5 password in a matter of seconds if they get access to the MYSQL database that is connected to the website on which you registered. Never use md5 it's a horrible way to treat your members. Use php inbuilt password_hash. Md5 is not safe at all please I beg you use password_hash.

Peter | April 26, 2016 2:02 PM |

well explained..nice and easy to follow. thank you very much

Kade | November 7, 2016 8:54 AM |

Very nice script, thank you. I like the separate txt file and auto-hash. If you are ever able to update it to include password_hash, no doubt many would benefit. The majority of tutorials for password_hash is with use of a database.