Create a Login Page Using PHP and MySQL


In this tutorial, we will learn how to create a simple authentication form using PHP and MySQL. This tutorial covers the fundamental concept of sessions and query execution.

How to Create a Login Page Using PHP and MySQL

I’m sure you have seen those simple login forms with user name and password that let you access the membership area. We will be creating something like that in our example.

Now, Let get started with our tutorial.

Create a database

Create a database ‘users’ in MySQL

Picture 1. Creating the database Users

Now create a simple table ‘members’

Picture 2. Creating the table Members

Now insert dummy data to test the code.
I have stored string ‘admin’ in the user_name, md5(1234) in the password, 1 in the active field.

The purpose of using md5() function on user_pass is to make it secure and encrypted. There is no way a user can decrypt an md5() string. The only way to verify the password is to take the md5() of the string being entered as the user password and compare it with the password being stored in the database.

The Logic

The logic is simple. Login.php will display a login form with two HTML input elements and a submit button. Once the user enters the credentials and clicks on the Login button, the data will is submitted to login_ac.php. The credentials being entered will be checked against the values being stored in the database.
If such a user exists, session variables are created, and the user will be redirected to dashboard.php else, the user will be redirected to login.php with the error code set to 1. The error message of incorrect username or password will be displayed at login.php

The user can sign out from the dashboard.

Now, if you have understood the primary flow or logic, Let’s dive into the code.

Copy paste the following code in login. php

<div class="login_form_div">	
    <h3>User Login!</h3>
    <?php if(isset($_GET['error'])){
            if($_GET['error']==1) {
              $msg = "Incorrect user name or password. Please try again!";
            }
            else{
              if($_GET['error']==2) {
                $msg = "You are not allowed to Access!";
              }
            }
            echo "<div class=\"errorbox\">".$msg." </div>";
    }?>
    <form class="" action="login_ac.php" method="post">
      <input type="text" name="username" value="" placeholder = "Enter user name" autofocus>
      <input type="password" name="userpass" value="" placeholder ="Enter your password">
      <input type="submit" name="submit" value="Login">
    </form>
  </div>
  <link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">

*{box-sizing:border-box;}
body{font-family: 'Open Sans', sans-serif; color:#333; font-size:14px; background-color:#dadada;}
.login_form_div{
  width:400px;
  height:340px;
position:absolute;
  top:50%;
  left:50%;
  margin-left:-200px;
  margin-top:-120px;
  background-color:white;
}
input{padding:10px; width:90%; margin:5px 15px;}
input[type="submit"]{outline:0; border:0; background-color:#ADCF1A; border-bottom:4px solid #8CBF1C;}
h3{text-align:center;  font-size:30px;}
.errorbox{padding:10px;  border:1px solid #c10909; background-color:#f6cbcb; width:70%; margin: 10px auto;}

Picture 3. Login Page Layout

Now create the file login_ac.php

<?php
session_start();
  $conn = mysqli_connect("localhost","root","","users");
  if(!$conn){
      echo "Error: Unable to connect to MySql";
      die();
  }

if($_POST['submit']){
  $user_name = $_POST['username'];
  $user_pass = $_POST['userpass'];
  $query = "select * from members where user_name='$user_name' and user_pass=md5('$user_pass')";

  $result = mysqli_query($conn, $query);
  $num_rows = mysqli_num_rows($result);
  if($num_rows==1){
    $_SESSION['logged'] = 1;
    $_SESSION['user'] = $user_name;
    $_SESSION['valid_user'] =1;
    header("Location:dashboard.php");

  }
  else{ header("Location:login.php?error=1");}

}
?>

In case the user enters an incorrect user name or password, the mysqli_num_rows will return 0.

 

Picture 4. Wrong Username or Password

Now create the file Dashboard.php

<?php
session_start();
if(!isset($_SESSION['logged']))
header("location:login.php?error=2");
?>
<!DOCTYPE html>
<html>
<head>
  <link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
<style>
*{box-sizing:border-box;}
body{font-family: 'Open Sans', sans-serif; color:#333; font-size:14px; background-color:#dadada;}
</style>
<body>
  <h3>Welcome <?php echo $_SESSION['user']; ?> !</h3>
  <p>
    <a href="signout.php">Sign Out</a>
  </p>
</body>
</html>
Picture 5. User Dashboard

And the file Signout.php

<?php
session_start();
$_SESSION = array();
 setcookie(session_name(), '', time() - 2592000, '/');
 session_destroy();

?>
<!DOCTYPE html>
<html>
<head>
  <link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
<style>
*{box-sizing:border-box;}
body{font-family: 'Open Sans', sans-serif; color:#333; font-size:14px; background-color:#dadada;}
</style>
<body>
  <h3>Good bye!</h3>
  <p>You have successfully sign out. </p>
  <p>

    <a href="login.php">Sign In</a>
  </p>
</body>
</html>
Picture 6. Sign out

The code below will determine if the user has been logged in or not. This will keep the user away from the unauthorized pages.

<?php
session_start();
if(!isset($_SESSION['logged']))
header("location:login.php?error=2");
?>

 

Related Articles

How to send an Email with attachment using PHP

Upload and Download Files Using PHP

Export data from MySQL to excel using php

Leave a Reply