hdr

How to Create a Secure Login Script in php and mysql

Welcome back guys, in this post I'm gonna to tell you about how to create a secure login script in PHP and MySQL.

so let's start.

Secure Login Script using PHP and MySQL

This is a Simple to Advanced to create a Login Script System using PHP and MySQL. In this script, a frame will be shown with two fields, username, and password. At the point when the client is submitting with legitimate username and password, at that point he can get to the verified page. Something else, clients again need to fill in the shape. This is a sequence from the last article Simple User Registration Script in PHP and MySql. If you need to take the next section, these are the connections.

Steps to create Secure Login Script in PHP and MySQL : 
  1. Initial step we will interface with the database. 
  2. At that point, we will choose the database. 
  3. We are checking if the frame is submitted or not. In this progression, we have two logics
  4. Imagine a scenario in which the shape is submitted. 
  5. If the shape is submitted, we are appointing the presented esteems on factors and checking the qualities are existing in the database or not. 
  6. On the off chance that the qualities submitted in the frame and the qualities in the database are equivalent, at that point we will make a session for the client. 
  7. If the qualities are not equivalent, then it will show a blunder message. 
  8. And then we check for the session, if the session exists, we will extraordinary him with the username, generally, the frame will be shown. 
  9. Consider the possibility that not the shape is submitted. 
  10. At the point when the client starts things out time, he will be shown with a square shape. 
  11. Client Name, Password and a submit catch.

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>
</form>
Now we should write the PHP code to check whether the user id and password are correct or not. You should write 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();
?>

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 = "";
   $hostname = "127.0.0.1";
   $db = "phplogin";
   $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 = "xtechnopediabcdefghijklmanopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
      $size = strlen($chars);
      for($i = 0;$i < $length;$i++) {
       $str .= $chars[rand(0,$size-1)];
      }
      return $str; /
     }
     $p_salt = rand_string(20); 
     $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 the above code.
This login system is  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.

No comments

Powered by Blogger.