Simple Login Page with PHP and MySQL

Login page is used to validate user based on their credentials.

Login Page takes user input and passes the data to server-side program. If user is authenticated then he can access the secure section of the website and it also helps to display content according to the user.

In this tutorial, We learn how you can create a simple Login page with PHP and MySQL.

Login Page with PHP and MySQL

Contents

Database table structure

We are using users table to validate a user.

CREATE TABLE `users` (
  `id` int(11) NOT NULL,
  `username` varchar(80) NOT NULL,
  `name` varchar(80) NOT NULL,
  `password` varchar(80) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

2) Configuration

Creating a config.php file for define database and other configuration.

<?php

session_start(); /* Session Start name */

$host = "localhost"; /* Database Host name */
$user = "root"; /* Database User */
$password = ""; /* Database Password */
$dbname = "tutorial"; /* Database name */

$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection is established or not. if not then stop execution with Connection failed error
if (!$con) {
 die("Connection failed: " . mysqli_connect_error());
}

3) HTML

Creating a index.php file in it we will Create a login page layout that has two input type elements for entering username and password and a button to submit the form. We are using bootstrap to design login page.

<html>
   <head>
      <title>Create simple login page with PHP and MySQL</title>
      <link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
      <script src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
      <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
      <!------ Include the above in your HEAD tag ---------->
      <link href="style.css?v=1" rel="stylesheet" type="text/css">
   </head>
   <body>
      <div id="login">
         <div class="container">
            <div id="login-row" class="row justify-content-center align-items-center">
               <div id="login-column" class="col-md-6">
                  <div id="login-box" class="col-md-12">
                     <form id="login-form" class="form" action="" method="post">
                        <h3 class="text-center text-info">Login</h3>
                        <span class="error"><?php echo $error_msg;?></span>
                        <div class="form-group">
                           <label for="username" class="text-info">Username:</label><br>
                           <input type="text" name="username" id="username" class="form-control">
                        </div>
                        <div class="form-group">
                           <label for="password" class="text-info">Password:</label><br>
                           <input type="text" name="password" id="password" class="form-control">
                        </div>
                        <div class="form-group submit_div">                               
                           <input type="submit" name="btn_submit" class="btn btn-info btn-md" value="submit">
                        </div>
                     </form>
                  </div>
               </div>
            </div>
         </div>
      </div>
   </body>
</html>
Login Page

4) CSS

We will write custom CSS in stlye.css file.

body {
  margin: 0;
  padding: 0;
  background-color: #17a2b8;
  height: 100vh;
}
#login .container #login-row #login-column #login-box {
  margin-top: 20px;
  max-width: 600px;
  height: 320px;
  border: 1px solid #9C9C9C;
  background-color: #EAEAEA;
}
#login .container #login-row #login-column #login-box #login-form {
  padding: 20px;
}
#login .container #login-row #login-column #login-box #login-form #register-link {
  margin-top: -85px;
}
.error{
  color: red;
}
.submit_div{
  text-align: center;
}

5) PHP

On the form submit first we check the username and password entered or not. If username and password are not empty then we execute a SELECT query to get record of user on the basis of username and password.

If the query returns user information then we will set “username” in session $_SESSION['username'] and redirect user to home.php page. otherwise display error message on top of the form.

<?php
   include "config.php";
   //define $error_msg='' in start.
   $error_msg='';  
    // Check form submit or not.
   if(isset($_POST['btn_submit'])){     
       // Escapes special characters in a string for use in an SQL query,
       $username = mysqli_real_escape_string($con,$_POST['username']);
       $password = mysqli_real_escape_string($con,$_POST['password']);
       $UserData=array();
       // check username and password is empty or not.
       if ($username != "" && $password != ""){        
           $sql_query = "select * from users where username='".$username."' and password='".$password."'";
           //run query
           $result = mysqli_query($con,$sql_query);
           //Fetch userdata from result.
           $UserData = mysqli_fetch_array($result);      
           // Check userdata is empty or not.
           if(!empty($UserData)){
               $_SESSION['username'] = $username;
               header('Location: home.php');
           }else{
               // Set error messages
              $error_msg = "Invalid username and password";
           }
       }
   }
?>

Homepage

Create a new home.php file. in it First, check whether the user is logged or not by checking the $_SESSION['username']variable. If $_SESSION['username']variable not set then redirect the user to index.php for login.

Also, create a logout button that destroy the current user session and redirect to index.php web page for login.

<?php
include "config.php";

// Check user login or not and username is not empty
if(!isset($_SESSION['username']) && !empty($_SESSION['username'])){    
    header('Location: index.php');
}

// Check login form submit or not.
if(isset($_POST['btn_logout'])){
    session_destroy();
    header('Location: index.php');
}
?>
<!doctype html>
<html>
    <head></head>
    <body>
        <h1>Homepage</h1>
        <form method='post' action="">
            <input type="submit" value="Logout" name="btn_logout">
        </form>
    </body>
</html>

7) Demo

8) Conclusion

In this tutorial, we showed how you can create a simple login page with PHP and MySQL. Please remember below listed key points when you create a login form.

  • You must have to start session first with session_start(); function at the top of a page or before you call session code.
session_start();
  • Put a User information in the session to track who is logged in and to detect the user when traversing to other pages. 
 $_SESSION['username'] = $username;

  • Destroy the session when user clicks the logout buttons.
  • if you have any issue then please print a query or check variable is set or not.

Be First to Comment

Leave a Reply

Your email address will not be published.