Create MySQL Injection free Secure Login System in PHP


Read {count} times since 2020

There were a lot of people who created tutorials to create a PHP Login System. But they were all vulnerable to MySQL Injection. In this post I’m going to demonstrate a login system free of this vulnerability. It is very secure. There are mysqli and PDO in PHP to escape these injections. We are going to use **PDO ( PHP Data Object **).

UPDATE – logSys

There is a new, free, better Advanced Login System which you can check out here.

First of all create a file named login.php, home.php, logout.php

Create Users Table

****For storing user information you have to create a table named users. Here is the SQL code to create the table.

CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` text NOT NULL,
`password` text NOT NULL,
`psalt` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
  1. The column username is to store the e-mail of the user. This e-mail is used as the username.
  2. The column password is to store user’s password which will be heavily encrypted using SHA256.
  3. The column psalt contains a random text to check if password is true.

Now we should add a user to the table. Execute the following SQL code to create a user.

INSERT INTO `users` (
 `id`, 
 `username`, 
 `password`, 
 `psalt`
) VALUES (
 NULL, 
 '[email protected]', 
 '4f8ee01c497c8a7d6f44334dc15bd44fe5acea9aed07f67e34a22ec490cfced1', 
 's*vl%/?s8b*b4}b/w%w4'
);

The user is inserted with the following values:

login.php

Create a login form :

<form method="POST" action="login.php" style="border:1px solid black;display:table;margin:0px auto;padding-left:10px;padding-bottom:5px;">
 <table width="300" cellpadding="4" cellspacing="1">
  <tr><td><td colspan="3"><strong>User Login</strong></td></tr>
  <tr><td width="78">E-Mail</td><td width="6">:</td><td width="294"><input size="25" name="mail" type="text"></td></tr>
  <tr><td>Password</td><td>:</td><td><input name="pass" size="25" type="password"></td></tr>
  <tr><td></td><td></td><td><input type="submit" name="Submit" value="Login"></td></tr>
 </table>
 Login System provided by <a target="_blank" href='http://sag-3.blogspot.com/2013/08/secure-injection-free-login-system-php.html'>Subins</a>
</form>

Now we should add the PHP code to check whether the username and password is correct. You should add the PHP code before </form> we just added in login.php.

<?php
session_start();
if(isset($_SESSION['user']) && $_SESSION['user']!=''){header("Location:home.php");}
$dbh=new PDO('mysql:dbname=db;host=127.0.0.1', 'username', 'password');/*Change The Credentials to connect to database.*/
$email=$_POST['mail'];
$password=$_POST['pass'];
if(isset($_POST) && $email!='' && $password!=''){
 $sql=$dbh->prepare("SELECT id,password,psalt FROM users WHERE username=?");
 $sql->execute(array($email));
 while($r=$sql->fetch()){
  $p=$r['password'];
  $p_salt=$r['psalt'];
  $id=$r['id'];
 }
 $site_salt="subinsblogsalt";/*Common Salt used for password storing on site. You can't change it. If you want to change it, change it when you register a user.*/
 $salted_hash = hash('sha256',$password.$site_salt.$p_salt);
 if($p==$salted_hash){
  $_SESSION['user']=$id;
  header("Location:home.php");
 }else{
  echo "<h2>Username/Password is Incorrect.</h2>";
 }
}
?>

home.php

<html><head></head>
<body>
<?
session_start();
if($_SESSION['user']==''){
 header("Location:login.php");
}else{
 $dbh=new PDO('mysql:dbname=db;host=127.0.0.1', 'root', 'backstreetboys');
 $sql=$dbh->prepare("SELECT * FROM users WHERE id=?");
 $sql->execute(array($_SESSION['user']));
 while($r=$sql->fetch()){
  echo "<center><h2>Hello, ".$r['username']."</h2></center>";
 }
}
?>
</body>
</html>

logout.php

This file is simple. Just add the following :

<?
session_start();
session_destroy();
?>

Now login using username as [email protected] and password as subinsiby. You will be redirected to home.php and it will say the following:

register.php

What’s logging in without registering ? Here’s a sample Registration page :

<?
session_start();
if(isset($_SESSION['user']) && $_SESSION['user']!=''){
 header("Location:home.php");
}
?>
<!DOCTYPE html>
<html>
 <head></head>
 <body>
 <form action="register.php" method="POST">
  <label>E-Mail <input name="user" /></label><br/>
  <label>Password <input name="pass" type="password"/></label><br/>
  <button name="submit">Register</button>
 </form>
 <?
  if(isset($_POST['submit'])){
   $musername = "root";
   $mpassword = "backstreetboys";
   $hostname = "127.0.0.1";
   $db = "p";
   $port = 3306;
   $dbh=new PDO('mysql:dbname='.$db.';host='.$hostname.";port=".$port,$musername, $mpassword);/*Change The Credentials to connect to database.*/
   if(isset($_POST['user']) && isset($_POST['pass'])){
    $password=$_POST['pass'];
    $sql=$dbh->prepare("SELECT COUNT(*) FROM `users` WHERE `username`=?");
    $sql->execute(array($_POST['user']));
    if($sql->fetchColumn()!=0){
     die("User Exists");
    }else{
     function rand_string($length) {
      $str="";
      $chars = "subinsblogabcdefghijklmanopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
      $size = strlen($chars);
      for($i = 0;$i < $length;$i++) {
       $str .= $chars[rand(0,$size-1)];
      }
      return $str; /* http://subinsb.com/php-generate-random-string */
     }
     $p_salt = rand_string(20); /* http://subinsb.com/php-generate-random-string */
     $site_salt="subinsblogsalt"; /*Common Salt used for password storing on site.*/
     $salted_hash = hash('sha256', $password.$site_salt.$p_salt);
     $sql=$dbh->prepare("INSERT INTO `users` (`id`, `username`, `password`, `psalt`) VALUES (NULL, ?, ?, ?);");
     $sql->execute(array($_POST['user'], $salted_hash, $p_salt));
     echo "Successfully Registered.";
    }
   }
  }
  ?>
 </body>
</html>

Note to change the Database credentials on above code.

This login system is totally 99% secure. It’s very hard to crack for a hacker and it’s completely **MySQL Injection **free. It took me less than 1 hour to create this system and create this post. Happy Logging. If you have any problems/suggestions/feedbacks just comment. I will help you.

Show Comments