This tutorial guides you in building a secure login system using PHP, MySQL and Ajax. It enables users to log in and log out. In this, PHP manages the server-side logic, MySQL stores user data, and Ajax handles client-side requests.



PHP, MySQL, and Ajax Secure Login System Interactive Demo

Create the Database

The first step is to create a database that will store user data. We will use MySQL for this purpose. Here is an example SQL query that creates a table called tbl_users:

CREATE TABLE `tbl_users` (
  `userid` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `email` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `password` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `status` enum('Unverified','Verified','Disabled') COLLATE utf8_unicode_ci NOT NULL DEFAULT 'Unverified',
  PRIMARY KEY (`userid`),
  UNIQUE KEY `email` (`email`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci

The table has five columns: userid, name, email, password, and status. The userid column serves as the primary key and auto-increments.

Create the Login Form

The next step is to create a login form that allows users to log in. Here is an example HTML form:

<form id="loginForm">
    <label for="email">Email</label>
    <input type="email" name="email" id="email" placeholder="Your email address" required>
    <span id="emailError"></span>

    <label for="password" class="form-label">Password</label>
    <input type="password" name="password" id="password" required>
    <span id="passwordError"></span>
    
    <input type="button" id="loginButton" value="Login">
    <div id="loginError"></div>
</form>

This form contains two fields: email and password. On submission, Ajax sends this data to the server for processing.

Handle the Login Request

Upon receiving the login request, the server validates the data and checks for a matching record in the tbl_users table. Here is a PHP script that handles the login request:

<?php session_start();
// Verify if the request is POST and an Ajax call
if ($_SERVER['REQUEST_METHOD'] === 'POST' && (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest')) {
    // Include the configuration file
    require("config.php");

    // Initialize response array and set Content-Type
    $response = [];
    header('Content-Type: application/json');

    // Sanitize the POST data
    $email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
    $password = filter_var($_POST['password'], FILTER_SANITIZE_STRING);

    // Perform validations
    if (empty($email) || empty($password)) {
        http_response_code(422);
        $response['message'] = 'Both email and password are required.';
    }
    else {
        // Prepare, bind, and execute SQL statement
        $stmt = mysqli_prepare($conn, "SELECT * FROM tbl_users WHERE email = ? AND password = ?");
        mysqli_stmt_bind_param($stmt, "ss", $email, $password);
        mysqli_stmt_execute($stmt);

        // Validate credentials
        $result = mysqli_stmt_get_result($stmt);
        if (mysqli_num_rows($result) != 1) {
            http_response_code(401);
            $response['message'] = 'Invalid email or password.';
        }

        // Fetch user details, and store it in session
        $userData = mysqli_fetch_assoc($result);

        // Check the status here
        if ($userData['status'] === 'Unverified') {
            http_response_code(403);
            $response['message'] = 'Your account is not verified.';
        } elseif ($userData['status'] === 'Disabled') {
            http_response_code(403);
            $response['message'] = 'Your account is disabled.';
        } elseif ($userData['status'] === 'Verified') {
            $_SESSION['userdata'] = $userData;
        } else {
            http_response_code(500);
            $response['message'] = 'An unknown error occurred.';
        }

        // Close resources
        mysqli_stmt_close($stmt);
        mysqli_close($conn);
    }
    // Output the JSON response
    echo json_encode($response);
    exit;
}
?>

Add JavaScript

Incorporate JavaScript to handle client-side form validation and Ajax calls. The script below accomplishes this:

<script>
    document.addEventListener("DOMContentLoaded", () => {
        const loginForm = document.getElementById("loginForm");
        const emailError = document.getElementById("emailError");
        const passwordError = document.getElementById("passwordError");
        const loginError = document.getElementById("loginError");

        document.getElementById("loginButton").addEventListener("click", () => {
            if (!loginForm.checkValidity()) {
                emailError.textContent = loginForm.email.checkValidity() ? "" : loginForm.email.validationMessage;
                passwordError.textContent = loginForm.password.checkValidity() ? "" : loginForm.password.validationMessage;
                return;
            }

            const xhr = new XMLHttpRequest();
            const email = document.getElementById("email").value;
            const password = document.getElementById("password").value;

            xhr.open("POST", "", true);
            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
            xhr.onreadystatechange = () => {
                if (xhr.readyState === 4) {
                    const response = JSON.parse(xhr.responseText);
                    if (xhr.status === 200) {
                        window.location.href = "dashboard.php";
                return; // Successful login
            }
            loginError.textContent = xhr.status === 500 ? "Something went wrong on the server. Please try again later." : response.message;
        }
    };
    xhr.send(`email=${email}&password=${password}`);
});
    });
</script>

Implement Logout Functionality

The final step is to create a logout functionality that allows users to log out. Here is a PHP script that logs out the user:

// Redirect to the home page if 'logout' is set
if(isset($_GET['logout'])){
    session_destroy(); // Destroy the session
    header('Location: ./'); // Redirect to home page
    exit;
}

This code terminates the session and redirects the user to the login page.

Conclusion

This tutorial guided you through creating a login system with PHP, MySQL, and Ajax. It covered database creation, login form design, and server-side and client-side request handling. Use this knowledge to enhance your web applications effectively.



Found This Page Useful? Share It!
Get the Latest Tutorials and Updates
Join us on Telegram