Simple Login Form In PHP With Mysql Database

By : PHPErrorCode May 29, 2017 2072 Views php,html,css

Every website uses simple Login module for their member. It is one of the most important security feature for any Website. It is important in Login Form we need to take care not to apply SQL Injection. For that we need to use prepared statement. Prepared Statement executes same SQL statement repeatedly. SO we will use Prepared Statement which will prevent SQL Injection.

In this form, we us two Field "Username" and "Password", If user submit valid username and password, then he can access his/her account. we also add "Remember Me" option that will store password in Browser cookie, so next time user We also use Call Back feature that will prevent user to go back after he log out. If user click on previous page, then browser will redirects to Login form.

Requirements for Sign-In webpage :
  1. HTML
  2. CSS
  3. PHP
  4. MySQL
  5. Xampp / Wamp server
Stap 1: first Create a Database :
  1. Open phpmyadmin
  2. Create database   as "tutorial"
  3. Click create table and name it as "user"
CREATE TABLE `user` (
  `id` int(11) NOT NULL,
  `user_name` varchar(25) NOT NULL,
  `email` varchar(50) NOT NULL,
  `password` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Step 2: Inserting data to the table UserName & Password :
INSERT INTO `user` (`id`, `email`, `password`) VALUES
(1, 'vikraminphp@gmail.com', 'demo@123');
Step 3: Front end code, Make HTML Structure of your login form for login.php

First of all we need to design the Sign-In webpage. Commonly what we see on a login webpage. There is user email and password form boxes and a button to sign in to the profile page of user.

<!DOCTYPE html>
<html>
<head>
  <title>Login</title>
  <link rel="stylesheet" href="custom.css">
  <script type="text/javascript" src="custom.js"></script>
</head>
<body>
  <form action="CheckLogin.php" method="post">
    <h2><span class="entypo-login"></span> Login</h2>
    <button class="submit"><span class="entypo-lock"></span></button>
    <span class="entypo-user inputUserIcon"></span>
    <input type="text" name="email" class="user" placeholder="urser Email" required="" 
      value="<?php if(isset($_COOKIE['user_name'])) { echo $_COOKIE['user_name']; } ?>" />
    <span class="entypo-key inputPassIcon"></span>
    <input type="password" name="password" class="pass" placeholder="password" required="" 
      value="<?php if(isset($_COOKIE['user_pass'])) { echo $_COOKIE['user_pass']; } ?>"/>
    <input type="checkbox" name="remember" value="true" class="remember" 
      <?php if (isset($_COOKIE['user_name'])) { echo 'checked'; } ?> 
    <span class="remember_span">Remember me</span>
  </form>
</body>
</html>
Step 4: Create A New File custom.js And Place The Js Below Into It.
$(".user").focusin(function(){
  $(".inputUserIcon").css("color", "#e74c3c");
}).focusout(function(){
  $(".inputUserIcon").css("color", "white");
});

$(".pass").focusin(function(){
  $(".inputPassIcon").css("color", "#e74c3c");
}).focusout(function(){
  $(".inputPassIcon").css("color", "white");
});
Step 5: Create A New File custom.css And Place The css Below Into It.
@import url(http://weloveiconfonts.com/api/?family=entypo);
@import url(http://fonts.googleapis.com/css?family=Roboto);
/* zocial */
[class*="entypo-"]:before {
  font-family: 'entypo', sans-serif;
}

*,
*:before,
*:after {
  -moz-box-sizing: border-box;
  -webkit-box-sizing: border-box;
  box-sizing: border-box; 
}
h2 {
  color:rgba(255,255,255,.8);
  margin-left:12px;
}
body {
  background: #272125;
  font-family: 'Roboto', sans-serif;
  
}
form {
  position:relative;
  margin: 50px auto;
  width: 380px;
  height: auto;
}
input {
  padding: 16px;
  border-radius:7px;
  border:0px;
  background: rgba(255,255,255,.2);
  display: block;
  margin: 15px;
  width: 300px;  
  color:white;
  font-size:18px;
  height: 54px;
}
input:focus {
  outline-color: rgba(0,0,0,0);
  background: rgba(255,255,255,.95);
  color: #e74c3c;
}
button {
  float:right;
  height: 121px;
  width: 50px;
  border: 0px;
  background: #e74c3c;
  border-radius:7px;
  padding: 10px;
  color:white;
  font-size:22px;
}
.inputUserIcon {
  position:absolute;
  top:68px;
  right: 80px;
  color:white;
}
.inputPassIcon {
  position:absolute;
  top:136px;
  right: 80px;
  color:white;
}
input::-webkit-input-placeholder {
  color: white;
}
input:focus::-webkit-input-placeholder {
  color: #e74c3c;
}
.remember_span{
  color: #cecece;
  font-size: 20px;
}
.remember{
  width: 12%;
  float: left;
  padding: 0px;
  height: auto;
  margin: 8px;
}
Step 6: Create A New File config.php And Place The Code Below Into It.

If you are following from previous user registration article, no need to create this file. Other wise create confing.php file.

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "tutorial";

	// Create connection
	$conn = new mysqli($servername, $username, $password, $dbname);

	// Check connection
	if ($conn->connect_error) 
	{
	    die("Connection failed: " . $conn->connect_error);
	}
?>
Step 7: Create A New File CheckLogin.Php And Place The Code Below Into It.
<?php
include('config.php');	
session_start();

//expiriry time. 86400 = 1 day (86400*30 = 1 month)
$expiry = time() + (86400 * 30);

$email=$_POST['email'];
$password=$_POST['password'];

if($result = $conn->prepare("SELECT * FROM user where email=?") or die($conn->connect_errno))
{
    // Bind the variables to the parameter as strings.
    $result->bind_param('s', $email);

    // Execute the prepared statement.
    $result->execute();

    // Gets a result set from a prepared statement.
    $result = $result->get_result();

    // Fetch the table data.
    $row = $result->fetch_assoc();

    if (password_verify($password , $row['password']))
    {
        if(!empty($_POST['remember']))
        {
            //setting cookie variable.
            setcookie('user_name', $email, $expiry);
            setcookie('user_pass', $password, $expiry);
        }

        $_SESSION['user']= $row['email'];
        header("location: Dashboard.php");
        $conn->close();
     }
     else
     {
         setcookie('user_name', $email, $expiry);
 	 header("location: login.php");
     }
} 
else
{
    header("location: Login.php");	
}
?>

Step 8: Create A New File header.php And Place The Code Below Into It.

header.php will verify the session, if there is no session it will redirect to login page.

<?php
rinclude('config.php');
session_start();
if(!isset($_SESSION['user'])){  
    header("Location:registration.php");
}
else
{
    $email= $_SESSION['user'];
    
    if($result = $conn->prepare("select * from user where email=?"))
    {
        // Bind the variables to the parameter as strings.
    	$result->bind_param('s', $text);
        
        // Execute the prepared statement.
	$result->execute();

        // Gets a result set from a prepared statement.
	$result = $result->get_result();

        // Fetch the table data.
    	$row = $result->fetch_assoc();
    }
    else
    {
	header("Location:registration.php");
    }
}
?>

Step 9: Dashboard.php
<?php include('header.php'); ?>
<!DOCTYPE html>
<html>
<head>
  <title>Desboard</title>
</head>
<body>
  <h1>Wellcome <?php echo $_SESSION['user']; ?></h1>
  <h1><a href="Logout.php">Logout</h1>
</body>
</html>
Step 10: Logout.php
<?php
session_start();
session_destroy();
session_unset();
header("location: login.php");
?>