PHP Admin Login

PHP Admin Login: Admin panels serve as the central hub for managing websites, applications, or databases. To protect sensitive data and functionality, It is necessary to implement a robust and secure login system.

php admin login

In this article, we’ll explore how to create a PHP admin panel login system, ensuring both security and user-friendliness.

Before Getting started with this tutorial, You must follow the previous step for Admin Panel basic configuration

Previous Step – Admin Panel Set Up

Steps to Create Admin Login in PHP

Now, You have to follow the below steps to log in to the admin panel

Create an Admin Login Form

This code represents the login form for the admin panel, where users can enter their email and password to log in. If there are any errors in the login process, those errors will be displayed in the error message paragraphs.

This form contains the following elements:

  • A heading that says “Admin Panel.”
  • An error message paragraph that displays any login-related errors, which are stored in the $login variable.
  • A form element with the method set to “post” for submitting login details.
  • Two input fields for email and password, with corresponding error messages displayed below each field. The error messages are stored in the $validateLogin array.
  • A “Forgot your Password” link.
  • A “Remember me Password” checkbox.
  • A “Login” button.

File Name – index.php

<?php

require_once('scripts/AdminLogin.php');
?>

<!DOCTYPE html>
<html>
<head>
    <title>Login Page</title>
    <link rel="stylesheet" href="public/css/login.css">
</head>
<body>
   
<div class="container-fluid">
    <div class="row">
        <div class="col-sm-6">
           
            <!--- login form-->
            <div class="login-form bg-light">
                <h1 class="text-success">Admin Panel</h1>
                <p class="text-danger"><?= $login ?? ''; ?></p>
                <form method="post">
                    <div class=" mb-3 mt-3">
                    <label for="email">Email</label>
                    <input type="text" class="form-control" name="emailAddress">
                    <p class="text-danger"><?= $validateLogin['emailErr'] ?? ''; ?></p>
                    </div>
                    
                    <div class=" mt-3 mb-3">
                    <label for="email">Password</label>
                    <input type="password" class="form-control" name="pass">
                    <p class="text-danger"><?= $validateLogin['passErr'] ?? ''; ?></p>
                    </div>
                    
                     <div class="row">
                        <div class="col-sm-6">
                        <div class="input-group mb-3 mt-3">
                            <label>
                                <a href="" class="text-success">Forgot your Password</a>
                            </label>
                        </div>
                        </div>
                        <div class="col-sm-6">
                        <div class="form-check input-group mb-3 mt-3">
                                <input class="form-check-input" type="checkbox"  name="remember"> 
                                <label class="form-check-label"> Remember me Password</label>
                            </div>
                        </div>
                     </div>
                  
                    <button type="submit" name="login" class="btn btn-success">Login</button>
                </form>
            </div>
            <!---- login form-->
       </div>
       <div class="col-sm-6"></div>
    </div>
</div>

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
</body>
</html>

Design Admin Login Page

Directory – admin/public/css/login.css

/* styles.css */
.login-container {
    display: flex;
    justify-content: center;
}
html, body{
    font-family: Verdana,sans-serif;
    overflow-x: hidden;
}
.login-form {
    flex: 1;
    padding: 100px 100px 0px 100px;
    border-radius: 5px;
    height: 100vh;
}

.login-form h1{
    text-align: center;
    text-transform: uppercase;
    font-size: 30px;
    padding-bottom: 21px;
}

.empty-space {
    flex: 2;
}

/* bootstrap5 css override */
.container-fluid{
    margin: 0px;
    padding-left: 0px !important;
    padding-right: 0px !important;
   
}

.form-control{
    border-radius: 0px !important;
    border: 0px !important;
    height: 45px;
    margin: 10px 0px;
    border-bottom: 2px solid !important;
}
.form-control:focus{
    box-shadow: unset !important;
    border-bottom: 2px solid #198754 !important;
}

Write PHP code to log in

This code is responsible for authenticating admin users. It first validates the user input, and if the input is valid, it attempts to log in the user by checking the credentials against a database table.

If the login is successful, it starts a session and redirects the user to a dashboard. Otherwise, it displays an error message.

Please note that the code snippet provided assumes that the database connection details and ‘database.php’ file contain the necessary code to connect to the database.

File Name – AdminLogin.php

<?php
require_once('../database.php');

class AdminLogin {

    private $conn;

    public function __construct($conn) {
        $this->conn = $conn;
    }

    public function login($emailAddress, $pass) {

        $loginErr = null;
        $query = "SELECT * FROM admins WHERE emailAddress = ? AND pass = ?";
        $stmt = $this->conn->prepare($query);
        $stmt->bind_param("ss", $emailAddress, $pass);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($result->num_rows == 1) {
            // Successful login
            session_start();
            $_SESSION['username'] = $username;
            header("Location: dashboard.php");
        } else {
            $loginErr = "Please enter valid admin credential";
            
        }
        return $loginErr;

    }

    public function validateLogin($emailAddress, $pass) {

        $error = false;
        $emailErr = null;
        $passErr = null;
        $validEmail = '/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/';

        if(empty($emailAddress)) {
            $emailErr = "Email Address is required";
            $error = true;
           
        } elseif(!preg_match($validEmail,$emailAddress)) {
            $emailErr = "Wrong email address";
            $error = true;
        }

        if(empty($pass)) {
            $passErr = "Password is required";
            $error = true;
        } 

        $errorInfo = [
            "error" => $error,
            "emailErr" => $emailErr,
            "passErr" => $passErr
        ];
        
        return $errorInfo;
    }
}

if (isset($_POST['login']) && $_SERVER["REQUEST_METHOD"] == "POST") {
    $emailAddress = $_POST['emailAddress'];
    $pass = $_POST['pass'];
    
    $loginSystem = new AdminLogin($conn);
    $validateLogin = $loginSystem->validateLogin($emailAddress, $pass);
    
    if (!$validateLogin['error']){
    
       $login = $loginSystem->login($emailAddress, $pass);
    }
}
?>

 

Explanation –

Database Connection: The code includes an external file for a database connection, suggesting that it relies on a database to manage admin logins. However, the details of the database connection are not provided in this code snippet.

AdminLogin Class: The code defines a PHP class named AdminLogin, which encapsulates the admin login functionality. This class likely provides methods to validate and process admin logins.

Login Validation (validateLogin method):

  • The validateLogin method is used to validate user input (email and password) for login.
  • It checks if the email address is not empty, is in a valid email format, and if the password is not empty.
  • It sets error flags and messages for email and password validation.

Login Process (login method):

  • The login method is responsible for the actual login process.
  • It constructs an SQL query to check if there’s a matching record in the “admins” table with the provided email address and password.
  • If a match is found, it starts a PHP session, sets a session variable ($_SESSION['username']), and redirects the user to a dashboard page.
  • If there’s no match, it sets an error message.

Form Handling: The code includes a section where it checks if a POST request is made and processes the form data for login. If there are no validation errors, it attempts to perform the login.

Error Handling: The code handles validation errors and stores them in the $errorInfo array, which can be used to provide feedback to the user.

Insert Admin Login Details

Before login to the admin panel, you should insert the admin login details in the ‘admins’ table through the phpMyAdmin.

Login to Admin Panel

Now, open your admin login in your web browser and then log in to the admin panel with the valid credentials. If your credential is correct then you will be redirected to the Dashboard Page otherwise you will get an error message.

Suggestion

This is a basic example of setting up a PHP admin panel login system. You should also add security measures, such as protecting against SQL injection and implementing password policies.

You have created an admin login system successfully. now, follow the next step to the Admin Dashboard Page

Next Step – PHP Admin Dashboard