Simple Login Form in PHP and MySQL

In this tutorial, you will get free source code to create a simple login form in PHP and MySQL. It is developed with complete validation. It will be very useful to develop the best login system. So, you can easily integrate it into your projects.

The login form is an integral part of a web application. It is used to access individual information from the websites. Many popular websites  Such as Facebook, Gmail, LinkedIn, Twitter & more have login features. Even you can use it to create an admin login panel for managing the front-end content dynamically.

Simple login Form in PHP

How to create a Simple Login Form Using PHP

The login form is created with two required fields like email & password. These fields have a backend validation to accept only valid& registered email address & password

Features –

  • Using PHP, It can send login data through the POST method.
  • Using MySQL, It can check registered users.
  • The login form does not allow invalid data and protects from the hacking
  • Login can convert illegal user input into legal input data.
  • You can’t get into the dashboard until you will not log in with valid credentials.
  • You can log out after login.

Before creating a login form in your project, you must have to create a signup/registration form. Because users can’t log in without signup/ register. If you don’t know to create a registration form, then there is no need to worry, you can also learn it on this website by clicking the following link.

Read Also  

Create Registration/signup Form using PHP

PHP Form Validation

Folder Structure

You should create the following folder structure. Otherwise, you can use the given login script directly in your project.

login-system/
    |__database.php
    |__login-form.php
    |__login-script.php
    |__dashboard.php
    |__logout.php
    |__style.css

 

1. Connect PHP login Script to MySQL Database

First of all, write the following MySQL database connection script to connect PHP login System with Database.

File Name – database.php

 <?php

$hostname     = "localhost"; // enter your hostname
$username     = "root";  // enter your table username
$password     = "";   // enter your password
$databasename = "codingstatus.com";  // enter your database
// Create connection 
$conn = new mysqli($hostname, $username, $password,$databasename);
 // Check connection 
if ($conn->connect_error) { 
die("Unable to Connect database: " . $conn->connect_error);
 }
?>

2. Create Login Form Using HTML

Now, configure the following steps to create a login form using HTML

  •  Include login-script.php using the following script. Don’t worry it will explain it in the next step.
  • Include external style.css
  • Also, include the following bootstrap4 libraries to create a responsive login form.
  • Write the HTML code to create a login form

File Name – login-form.php

 <?php

include('login-script.php');
?>

<!DOCTYPE html>
<html lang="en">
<head>
  <title>PHP Login Form</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <!--bootstrap4 library linked-->
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<style type="text/css">
  .registration-form{
     background: #f7f7f7;
     padding: 20px;
     border: 1px solid orange;
     margin: 50px 0px;
   }
   .err-msg{
     color:red;
   }
   .registration-form form{
     border: 1px solid #e8e8e8;
     padding: 10px;
     background: #f3f3f3;
   }
</style>
</head>
<body>

<div class="container-fluid">
 <div class="row">
   <div class="col-sm-4">
   </div>
   <div class="col-sm-4">
    
    <!--====registration form====-->
    <div class="registration-form">
      <h4 class="text-center">PHP Login Form</h4>
      <p class="text-success text-center"><xmp>&lt;?php <xmp>echo $login;
?>
</p>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">

        
        <!--// Email//-->
        <div class="form-group">
            <label for="email">Email:</label>
            <input type="text" class="form-control" id="email" placeholder="Enter email" name="email">
            <p class="err-msg">
                
<?php if($emailErr!=1){ echo $emailErr; } ?>

            </p>
        </div>
        
        <!--//Password//-->
        <div class="form-group">
            <label for="pwd">Password:</label>
            <input type="password" class="form-control"  placeholder="Enter password" name="password">
            <p class="err-msg">
                
<?php if($passErr!=1){ echo $passErr; } ?>

            </p>
        </div>

        
        <button type="submit" class="btn btn-danger" value="login" name="register">Login</button>
      </form>
    </div>
   </div>
   <div class="col-sm-4">
   </div>
 </div>
  
</div>

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
</body>
</html>

 

4. Create a Login Script Using PHP and MySQL

Before writing a login script, you should understand the following points.

  • Include database connection file using require_once('database.php').
  • Assign a connection variable $conn to a new variable $db.
  • Check registration data are set using isset($_POST['submit']), if these are set then validate email & password using legal_input() function.
  • If both email & password  are validated successfully, call a custom function login() to process to login by checking valid credentials
  • If given credentials are already registered, it will redirect to the dashboard page.

File Name – login-script.php

<?php

require('database.php');
$db= $conn; // assign  your connection varibale

// by default, error messages are empty
$login=$emailErr=$passErr='';
  
 extract($_POST);
if(isset($_POST['submit']))
{
   
   //input fields are Validated with regular expression
   $validName="/^[a-zA-Z ]*$/";
   $validEmail="/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/";
   
 
//Email Address Validation
if(empty($email)){
  $emailErr="Email is Required"; 
}
else if (!preg_match($validEmail,$email)) {
  $emailErr="Invalid Email Address";
}
else{
  $emailErr=true;
}
    
// password validation 
if(empty($password)){
  $passErr="Password is Required"; 
} 
else{
   $passErr=true;
}

// check all fields are valid or not
if( $emailErr==1 && $passErr==1)
{
 
   //legal input values
   $email=     legal_input($email);
   $password=  legal_input(md5($password));
   
   // call login function
   $login=login($email,$password);

}

}

// convert illegal input value to ligal value formate
function legal_input($value) {
  $value = trim($value);
  $value = stripslashes($value);
  $value = htmlspecialchars($value);
  return $value;
}

// function to insert user data into database table
function login($email,$password){

  global $db;

   // checking valid email
  $sql="SELECT email FROM users WHERE email= ?";
  $query = $db->prepare($sql);
  $query->bind_param('s',$email); 
  $query->execute();
  $exec=$query->get_result();
  if($exec)
  {
  if($exec->num_rows>0){

    // checking email and password
    $loginSql="SELECT email, password FROM users WHERE email=? AND password=?";
    $loginQuery = $db->prepare($loginSql);
    $loginQuery->bind_param('ss',$email, $password); 
    $loginQuery->execute();
    $execQuery=$loginQuery->get_result();
    if($execQuery)
    {
    if($execQuery->num_rows>0){

      session_start();
      $_SESSION['email']=$email;
      header("location:dashboard.php");
    }else{
      return "Your Password is wrong";
    }

  }else{
  return $db->error;
  }


  }
  else
  {
    return $email." is not registered";
  }
}else{
  return $db->error;
}
    
    
}
?>

 

5. Create Dashboard Using HTML and PHP

  • To create a dashboard, you have to do the following things –
  • Start session using session_start()
  • Assign session login email $_SESSION['email'] to a new variable $email_address
  • If the session login email is empty, it will redirect to the login form page. means that you can’t directly open the dashboard page without login.

File Name – dashboard.php

<?php

session_start();
$email_address= $_SESSION['email'];
if(empty($email_address))
{
  header("location:login.php");
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Login Dashboard</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">

</head>
<body>

<div class="header">
<h1>Welcome to Dashboard  <a href="logout.php">Logout</a></h1>
</div>
<div class="user-box">
    <div class="user-detail">
      <p>Your Email Address</p>
      <h3>
      
<?php

        echo $email_address;
      
?>

    </h3>
    </div>
  </div>

</body>
</html>

 

6. Create Logout Script Using PHP

You can quickly log out by writing the following few lines of PHP code.

  • First of all, start the session using session_start()
  • Destroy session using session_destroy()
  • Redirect to the login page after logout.

File Name – logout.php

<?php

session_start();
session_destroy();
header("location:login.php");
?>

 

My Suggestion

Dear Developers, I hope you have learned to create a simple login form using PHP. If you have any doubts or questions related to this tutorial, you can ask me through the below comment box. I will reply as soon as possible.

Thanks For giving time to this tutorial…

Categories PHP

6 thoughts on “Simple Login Form in PHP and MySQL”

  1. Hi,
    I enjoy your tutorials so much, they are very clear and explained for beginners like me, so I really appreciate that,
    the only thing that is bugging me is the use of Mysqli instead of PDO, I’ve read so much about the benefits of PDO and it’s taking me a lot of time changing the “Mysqli ” part of your tutorials to PDO, apart of that.. you are doing an amazing job, thank you.

    Reply
    • Hi Ali,
      Thanks for giving useful suggestions… I’m glad about your interest in my tutorials… I will definitely share upcoming tutorials with PDO, MySQLi procedural, MySQLi Object-oriented soon. Even I will update old tutorials with PDO

      Reply
  2. hello sir
    i integrated this into my system which already have a sql DB, but the form is not working, its just load and show no error or anything, can you assist please.
    i love your tutrotial they are helping me a lot in learning PHP.

    thank you.

    Reply
  3. sir how to fixed this error: “Unable to Connect database: Access denied for user ‘php_users_login’@’localhost’ (using password: YES)”

    Reply

Leave a Comment