Create a Modern PHP Login and Registration System with Tailwind CSS

After learning the basics of web development, creating a PHP login and registration system is the first major step for every web developer. Whether you're building a personal blog, a company website, or a full-fledged online application, a secure and reliable user login system is essential. This is the system that allows people to create accounts, log in, and securely access personalized information or services. Without it, your website would remain static—just a collection of pages with no personal interaction.

PHP Login System

This project isn't just about writing a few lines of code. It teaches you how the different parts of a web application connect and communicate. You'll learn how HTML handles form structure, how CSS adds design and styling, and how PHP works behind the scenes to process, verify, and store user data. You'll also understand the crucial role databases play—acting as a secure storage area for user information like usernames, passwords, and email addresses. Once you've built this system, you'll have a clear understanding of how real-world websites like Facebook or LinkedIn manage their login systems on a smaller scale.

In this tutorial, we'll walk through a step-by-step process to build a complete login and registration system using PHP, MySQL, HTML, and CSS. We'll start by setting up a database, then move on to creating the registration form, securely storing user data, and finally building a working login page. We'll also cover session management, password hashing, and a simple logout feature. Everything will be explained in simple, conversational language, with examples you can try immediately. So, even if you're just starting out, by the end of this guide, you'll have your own working login and registration system—ready to use and easy to customize. Source code

Step 1: Set Up the Database

Before creating the login system, the first step is to create a database. This database will securely store all user information, such as usernames, email addresses, and passwords. Setting up a structured table ensures that your system can efficiently manage user registration and login. Even if you're new to PHP or MySQL, properly preparing the database lays a strong foundation for the rest of the project.


    <?php
        CREATE TABLE IF NOT EXISTS `users` (
        `id` int(11) NOT NULL AUTO_INCREMENT,
        `name` varchar(255) NOT NULL,
        `email` varchar(255) NOT NULL UNIQUE,
        `mobile` varchar(20) NOT NULL,
        `password` varchar(255) NOT NULL,
        `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
        `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        PRIMARY KEY (`id`)
        );
    ?>


Explanation of the SQL Query

  1. id: This is a unique identifier for each user. It is auto-incrementing, meaning each new user automatically receives a new ID. This makes it easy to reference users in your system.
  2. name: Stores the user's full name. It is marked as NOT NULL to prevent registration without a name.
  3. email: Stores the user's email address. The UNIQUE constraint ensures that no two users can register with the same email. This is important because email is often used as a login identifier.
  4. mobile: Stores the user's mobile number. NOT NULL ensures that every user must provide a mobile number.
  5. password: This field stores the user's hashed password. Never store plain text passwords – always use PHP's password_hash() function when inserting into this column.
  6. created_at: Automatically records the time of user registration. This helps in tracking new users.
  7. updated_at: The timestamp is automatically updated whenever the user's data is modified. This is useful when you allow users to update their profiles.
  8. Primary Key (id): The id column is the primary key, which ensures that each user record is uniquely identifiable.
By carefully setting up this table, you lay a solid foundation for a secure and functional login system. Once the table is ready, you can begin creating the registration and login forms.

Step 2: Create Login and Registration Forms with View Files

Next, you'll need to create the forms that users will interact with. This includes both a registration form for new users and a login form for returning users. The forms should be clean, simple, and user-friendly, including basic information such as username, email, and password. A well-designed form not only improves the user experience but also makes it easier for users to complete registration and login without any confusion.


    login.php

    <?php
        ob_start();
        session_start();
        require_once('../1config/connection.php');
        require_once('../1config/common_function.php');
        emailSet(); // Redirect to dashboard if already logged in
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Login - Login System</title>
        <script src="https://cdn.tailwindcss.com"></script>
        <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
        <link rel="stylesheet" href="../4assets/css/style.css">

        <style>
            .toast {
                position: fixed;
                top: 20px;
                right: 20px;
                z-index: 9999;
                animation: slideIn 0.3s ease-out;
            }
            @keyframes slideIn {
                from { transform: translateX(400px); opacity: 0; }
                to { transform: translateX(0); opacity: 1; }
            }
            @keyframes slideOut {
                from { transform: translateX(0); opacity: 1; }
                to { transform: translateX(400px); opacity: 0; }
            }
            .toast.hide {
                animation: slideOut 0.3s ease-in forwards;
            }
        </style>
    </head>
    <body class="bg-gray-50 min-h-screen flex items-center justify-center p-4">
       
        <!-- Toast Notification -->
        <?php
            $toast = getToast();
            if($toast):
                $bg_color = $toast['type'] == 'success' ? 'bg-green-500' : ($toast['type'] == 'error' ? 'bg-red-500' : 'bg-yellow-500');
                $icon = $toast['type'] == 'success' ? 'fa-check-circle' : ($toast['type'] == 'error' ? 'fa-times-circle' : 'fa-exclamation-triangle');
            ?>
            <div id="toast" class="toast <?php echo $bg_color; ?> text-white px-6 py-4 rounded-lg shadow-lg flex items-center space-x-3">
                <i class="fas <?php echo $icon; ?> text-xl"></i>
                <span><?php echo htmlspecialchars($toast['message']); ?></span>
                <button onclick="closeToast()" class="ml-4 text-white hover:text-gray-200"><i class="fas fa-times"></i></button>
            </div>
        <?php endif; ?>

        <!-- Login Form -->
        <div class="w-full max-w-md">
            <div class="bg-white rounded-2xl shadow-2xl overflow-hidden">
                <!-- Header -->
                <div class="bg-indigo-600 py-8 px-6 text-center">
                    <h1 class="text-3xl font-bold text-white">Welcome Back</h1>
                    <p class="text-indigo-100 mt-2">Login to your account</p>
                </div>
               
                <!-- Form -->
                <form action="../2managment/login.php" method="POST" class="p-8 space-y-6">
                    <!-- Email -->
                    <div class="relative">
                        <label class="block text-sm font-medium text-gray-700 mb-2"><i class="fas fa-envelope text-indigo-600 mr-2"></i>Email Address</label>
                        <input type="email" name="email" required  class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent transition-all" placeholder="Enter your email" autofocus="true">
                    </div>
                   
                    <!-- Password -->
                    <div class="relative">
                        <label class="block text-sm font-medium text-gray-700 mb-2"><i class="fas fa-lock text-indigo-600 mr-2"></i>Password</label>
                        <input type="password" name="password" required class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent transition-all" placeholder="Enter your password">
                    </div>
                   
                    <!-- Remember & Forgot -->
                    <div class="flex items-center justify-between">
                        <label class="flex items-center">
                            <input type="checkbox" class="w-4 h-4 text-indigo-600 border-gray-300 rounded focus:ring-indigo-500">
                            <span class="ml-2 text-sm text-gray-600">Remember me</span>
                        </label>
                        <a href="#" class="text-sm text-indigo-600 hover:text-indigo-700 font-medium">Forgot Password?</a>
                    </div>
                   
                    <!-- Submit Button -->
                    <button type="submit" name="submit"  class="w-full bg-indigo-600 text-white py-3 rounded-lg font-semibold hover:bg-indigo-700 transition-all transform hover:scale-[1.02] active:scale-[0.98] shadow-md">
                        <i class="fas fa-sign-in-alt mr-2"></i>Login
                    </button>
                   
                    <!-- Register Link -->
                    <div class="text-center text-sm text-gray-600">
                        Don't have an account?
                        <a href="registeration.php" class="text-indigo-600 hover:text-indigo-700 font-semibold">Register now</a>
                    </div>
                </form>
            </div>
           
            <!-- Footer -->
            <p class="text-center text-gray-600 text-sm mt-6">&copy; <?php echo date('Y'); ?> Login System. All rights reserved.</p>
        </div>

        <script>
            setTimeout(() => {
                const toast = document.getElementById('toast');
                if(toast) {
                    toast.classList.add('hide');
                    setTimeout(() => toast.remove(), 300);
                }
            }, 4000);
           
            function closeToast() {
                const toast = document.getElementById('toast');
                if(toast) {
                    toast.classList.add('hide');
                    setTimeout(() => toast.remove(), 300);
                }
            }
        </script>
    </body>
    </html>


This login.php file creates a complete login page, utilizing HTML, CSS (Tailwind + custom), and PHP session handling. The page manages user sessions at the start with `session_start()` and `ob_start()`, and the `emailset()` function checks if the user is already logged in, redirecting them to the dashboard if so. The page also includes a toast notification system at the top, which animates and displays success, error, or warning messages in the top-right corner of the screen. These notifications auto-hide after 4 seconds and can also be manually dismissed by the user, improving the user experience.

The main content of the page is a stylish login form that uses Tailwind CSS and custom styling to provide a responsive and modern look. The form includes email and password fields with labels and icons, as well as a "Remember me" checkbox and a "Forgot password?" link. The submit button features hover and active animations, making the interaction smooth and engaging. A registration link is provided at the bottom, directing new users to registration.php, and the page footer displays a copyright notice. This modular structure makes the page easy to maintain and scale.



    registeration.php
    <?php
        ob_start();
        session_start();
        require_once('../1config/connection.php');
        require_once('../1config/common_function.php');
        emailSet(); // Redirect to dashboard if already logged in
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Register - Login System</title>
        <script src="https://cdn.tailwindcss.com"></script>
        <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
        <style>
            .toast {
                position: fixed;
                top: 20px;
                right: 20px;
                z-index: 9999;
                animation: slideIn 0.3s ease-out;
            }
            @keyframes slideIn {
                from { transform: translateX(400px); opacity: 0; }
                to { transform: translateX(0); opacity: 1; }
            }
            @keyframes slideOut {
                from { transform: translateX(0); opacity: 1; }
                to { transform: translateX(400px); opacity: 0; }
            }
            .toast.hide {
                animation: slideOut 0.3s ease-in forwards;
            }
        </style>
    </head>
    <body class="bg-gray-50 min-h-screen flex items-center justify-center p-4">
       
        <!-- Toast Notification -->
        <?php
        $toast = getToast();
        if($toast):
            $bg_color = $toast['type'] == 'success' ? 'bg-green-500' : ($toast['type'] == 'error' ? 'bg-red-500' : 'bg-yellow-500');
            $icon = $toast['type'] == 'success' ? 'fa-check-circle' : ($toast['type'] == 'error' ? 'fa-times-circle' : 'fa-exclamation-triangle');
        ?>
        <div id="toast" class="toast <?php echo $bg_color; ?> text-white px-6 py-4 rounded-lg shadow-lg flex items-center space-x-3">
            <i class="fas <?php echo $icon; ?> text-xl"></i>
            <span><?php echo htmlspecialchars($toast['message']); ?></span>
            <button onclick="closeToast()" class="ml-4 text-white hover:text-gray-200">
                <i class="fas fa-times"></i>
            </button>
        </div>
        <?php endif; ?>

        <!-- Registration Form -->
        <div class="w-full max-w-md">
            <div class="bg-white rounded-2xl shadow-2xl overflow-hidden">
                <!-- Header -->
                <div class="bg-indigo-600 py-8 px-6 text-center">
                    <h1 class="text-3xl font-bold text-white">Create Account</h1>
                    <p class="text-purple-100 mt-2">Join us today!</p>
                </div>
               
                <!-- Form -->
                <form action="../2managment/register.php" method="POST" class="p-8 space-y-5">
                    <!-- Name -->
                    <div class="relative">
                        <label class="block text-sm font-medium text-gray-700 mb-2">
                            <i class="fas fa-user text-purple-600 mr-2"></i>Full Name
                        </label>
                        <input type="text" name="name" required autocomplete="off"
                            class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-600 focus:border-transparent transition-all"
                            placeholder="Enter your name">
                    </div>
                   
                    <!-- Email -->
                    <div class="relative">
                        <label class="block text-sm font-medium text-gray-700 mb-2">
                            <i class="fas fa-envelope text-purple-600 mr-2"></i>Email Address
                        </label>
                        <input type="email" name="email" required autocomplete="off"
                            class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-600 focus:border-transparent transition-all"
                            placeholder="Enter your email">
                    </div>
                   
                    <!-- Contact -->
                    <div class="relative">
                        <label class="block text-sm font-medium text-gray-700 mb-2">
                            <i class="fas fa-phone text-purple-600 mr-2"></i>Contact Number
                        </label>
                        <input type="text" name="contact" required autocomplete="off"
                            class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-600 focus:border-transparent transition-all"
                            placeholder="Enter your contact number">
                    </div>
                   
                    <!-- Password -->
                    <div class="relative">
                        <label class="block text-sm font-medium text-gray-700 mb-2">
                            <i class="fas fa-lock text-purple-600 mr-2"></i>Password
                        </label>
                        <input type="password" name="password" required autocomplete="off"
                            class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-600 focus:border-transparent transition-all"
                            placeholder="Create a password">
                    </div>
                   
                    <!-- Submit Button -->
                    <button type="submit" name="submit"
                            class="w-full bg-indigo-600 text-white py-3 rounded-lg font-semibold hover:bg-indigo-700 transition-all transform hover:scale-[1.02] active:scale-[0.98] shadow-md">
                        <i class="fas fa-user-plus mr-2"></i>Register
                    </button>
                   
                    <!-- Login Link -->
                    <div class="text-center text-sm text-gray-600">
                        Already have an account?
                        <a href="login.php" class="text-purple-600 hover:text-purple-700 font-semibold">Login now</a>
                    </div>
                </form>
            </div>
           
            <!-- Footer -->
            <p class="text-center text-white text-sm mt-6">&copy; <?php echo date('Y'); ?> Login System. All rights reserved.</p>
        </div>

        <script>
            setTimeout(() => {
                const toast = document.getElementById('toast');
                if(toast) {
                    toast.classList.add('hide');
                    setTimeout(() => toast.remove(), 300);
                }
            }, 4000);
           
            function closeToast() {
                const toast = document.getElementById('toast');
                if(toast) {
                    toast.classList.add('hide');
                    setTimeout(() => toast.remove(), 300);
                }
            }
        </script>
    </body>
    </html>
   

This register.php file creates a complete user registration page using PHP, HTML, and Tailwind CSS. Session handling is implemented at the top of the page with session_start() and ob_start(), and the emailset() function checks if the user is already logged in, redirecting them to the dashboard if they are. The page also features a toast notification system that displays success, error, or warning messages in an animated way in the top-right corner of the screen and automatically hides after 4 seconds. Users can also manually close the notifications, further enhancing the user experience.

The main content of the page is a stylish registration form that provides a responsive and modern design. The form includes fields for full name, email, contact number, and password, each with corresponding labels and icons. The submit button has hover and active animations that make interaction smooth. Below the form is a link that directs already registered users to login.php. The page layout is modular, making maintenance and future updates easier. The footer displays a copyright notice, and the Tailwind CSS classes give the form elements a professional and user-friendly look.

Step 3: Create a connection to the database



    connection.php
    <?php
        try {
            $hostname = 'localhost';
            $username = 'root';
            $password = '';
            $database = 'loginsystem';
           
            $conn = mysqli_connect($hostname, $username, $password, $database);
           
            if(!$conn) {
                throw new Exception('Database connection failed: ' . mysqli_connect_error());
            }
           
            mysqli_set_charset($conn, "utf8mb4");
           
        } catch(Exception $e) {
            die('Connection Error: ' . $e->getMessage());
        }
    ?>


This PHP script establishes a connection to a MySQL database using the mysqli extension. It first defines the database credentials: hostname (localhost), username (root), password (empty), and database name (login_system). It then attempts to connect using mysqli_connect(), and if the connection fails, it throws an exception with a specific error message. Upon successful connection, it sets the character set to utf8mb4 to properly handle Unicode characters. If any error occurs during the connection process, the catch block halts execution and displays a descriptive connection error message, ensuring the application does not proceed without a valid database connection.

Step 4: Write the Backend Code



    2managment\login.php
    <?php
        ob_start();
        session_start();
        require_once('../1config/connection.php');
        require_once('../1config/common_function.php');

        try {
            if(isset($_POST['submit'])) {
                // Validate input
                if(empty($_POST['email']) || empty($_POST['password'])) {
                    throw new Exception('Email and password are required');
                }
               
                $email = mysqli_real_escape_string($conn, trim($_POST['email']));
                $password = $_POST['password'];
               
                // Validate email format
                if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                    throw new Exception('Invalid email format');
                }
               
                // Find user
                $query = "SELECT * FROM `users` WHERE `email` = '$email'";
                $result = mysqli_query($conn, $query);
               
                if(!$result) {
                    throw new Exception('Database query failed: ' . mysqli_error($conn));
                }
               
                $find_record = mysqli_fetch_assoc($result);
               
                if($find_record) {
                    // Verify password
                    if(password_verify($password, $find_record['password'])) {
                        // Login successful
                        $_SESSION['emailID'] = $email;
                        $_SESSION['user_id'] = $find_record['id'];
                        $_SESSION['user_name'] = $find_record['name'];
                        last_activity();
                       
                        setToast('success', 'Login successful! Welcome back.');
                        header('location:../3view/pages/dashboard.php');
                        exit();
                    } else {
                        throw new Exception('Incorrect password');
                    }
                } else {
                    throw new Exception('No account found with this email');
                }
            } else {
                throw new Exception('Invalid request');
            }
           
        } catch(Exception $e) {
            setToast('error', $e->getMessage());
            header('location:../3view/login.php');
            exit();
        }
    ?>


This code handles the backend logic for user login. First, sessions and output buffering are enabled with `session_start()` and `ob_start()`, and the database connection from `connection.php` and helper functions from `common_function.php` are included. The code is written within a try-catch block, which gracefully handles errors and provides appropriate feedback to the user. If the form has been submitted (isset($_POST['submit'])), the email and password fields are checked; an exception is thrown if either is empty. The email is then sanitized (mysqli_real_escape_string) and trimmed, and the email format is validated (filter_var).

Next, a database query is run to check if the user exists. If the user is found, the password is checked using the `password_verify()` function. If the password is correct, session variables are set (emailID, user_id, user_name), and the `last_activity()` function is called, which tracks user activity. On success, a toast message is set, and the user is redirected to the dashboard. If the password is incorrect or the account does not exist, an exception is thrown, and the user is redirected back to the login page with an error message. This approach makes the login process secure, user-friendly, and fault-tolerant.


    2managment\register.php
    <?php
        ob_start();
        session_start();
        require_once('../1config/connection.php');
        require_once('../1config/common_function.php');

        try {
            if(isset($_POST['submit'])) {
                // Validate input
                if(empty($_POST['name']) || empty($_POST['email']) || empty($_POST['contact']) || empty($_POST['password'])) {
                    throw new Exception('All fields are required');
                }
               
                $name = mysqli_real_escape_string($conn, trim($_POST['name']));
                $email = mysqli_real_escape_string($conn, trim($_POST['email']));
                $contact = mysqli_real_escape_string($conn, trim($_POST['contact']));
                $password = $_POST['password'];
               
                // Validate email format
                if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                    throw new Exception('Invalid email format');
                }
               
                // Validate password length
                if(strlen($password) < 6) {
                    throw new Exception('Password must be at least 6 characters long');
                }
               
                // Validate contact number
                if(!preg_match('/^[0-9]{10}$/', $contact)) {
                    throw new Exception('Contact number must be 10 digits');
                }
               
                // Check if email already exists
                $check_query = "SELECT * FROM `users` WHERE `email` = '$email'";
                $check_result = mysqli_query($conn, $check_query);
               
                if(!$check_result) {
                    throw new Exception('Database query failed: ' . mysqli_error($conn));
                }
               
                $find_mail = mysqli_fetch_assoc($check_result);
               
                if($find_mail) {
                    throw new Exception('Email already registered. Please login instead.');
                }
               
                // Hash password
                $password_encryption = password_hash($password, PASSWORD_BCRYPT);
               
                // Insert new user
                $insert_query = "INSERT INTO `users` (`name`, `email`, `mobile`, `password`) VALUES ('$name', '$email', '$contact', '$password_encryption')";
                $complete_registration = mysqli_query($conn, $insert_query);
               
                if(!$complete_registration) {
                    throw new Exception('Registration failed: ' . mysqli_error($conn));
                }
               
                // Get the newly created user ID
                $user_id = mysqli_insert_id($conn);
               
                // Auto login after registration
                $_SESSION['emailID'] = $email;
                $_SESSION['user_id'] = $user_id;
                $_SESSION['user_name'] = $name;
                last_activity();
               
                setToast('success', 'Registration successful! Welcome to Login System.');
                header('location:../3view/pages/dashboard.php');
                exit();
               
            } else {
                throw new Exception('Invalid request');
            }
           
        } catch(Exception $e) {
            setToast('error', $e->getMessage());
            header('location:../3view/registeration.php');
            exit();
        }
    ?>


This code securely manages the user registration process. First, `session_start()` and `ob_start()` are called to enable session and output buffering, and the database connection and helper functions are included (connection.php and common_functions.php). The code is written within a try-catch block to gracefully handle errors and display user-friendly messages. If the registration form is submitted (isset($_POST['submit'])), all fields (name, email, contact, password) are validated. Email format, password length (minimum 6 characters), and contact number (exactly 10 digits) are validated. If validation fails, an exception is thrown, and the user is redirected back with an appropriate error message.

Next, a database query checks if the email is already registered. If the email exists, an exception is thrown. Otherwise, the password is securely hashed using `password_hash()`, and the user's data is inserted into the database. After setting session variables (emailID, user_id, user_name) for auto-login, the `last_activity()` function is called, which tracks user activity. Upon successful registration, a toast message is set, and the user is redirected to the dashboard. If any error occurs, the exception is caught, and the user is redirected back to the registration page. This ensures the registration process is secure, validated, and seamlessly handled.



    2managment\logout.php
    <?php
    ob_start();
    session_start();
    require_once('../1config/connection.php');
    require_once('../1config/common_function.php');

    try {
        // Clear all session data
        session_unset();
        session_destroy();
       
        // Start new session for toast message
        session_start();
        setToast('success', 'Logged out successfully');
       
        header('location:../3view/login.php');
        exit();
       
    } catch(Exception $e) {
        // Even if there's an error, redirect to login
        session_start();
        setToast('warning', 'Logout completed');
        header('location:../3view/login.php');
        exit();
    }
    ?>
   

This file first starts the session (session_start()) and enables output buffering (ob_start()). It then includes the database connection and common functions (connection.php and Common_function.php) to allow the use of helper functions like setToast(). The code is written within a try-catch block to handle errors. The logout process begins by clearing all session data using session_unset() and session_destroy(), effectively ending the user's login session and ensuring a secure logout.

Afterward, a new session is started, and a toast message is set (setToast('success', 'Successfully logged out')) to provide the user with feedback that the logout was successful. The user is then redirected to the login page using header('location:../3view/login.php'). If any unexpected error occurs, the catch block also starts a session, displays a warning message, and redirects the user to the login page. This approach makes the logout process secure, user-friendly, and error-tolerant.



    2managment\check_session.php
    <?php
        session_start();
        require_once('../1config/common_function.php');

        header('Content-Type: application/json');

        try {
            $logged_out = autologout();
           
            if($logged_out) {
                echo json_encode(['logged_out' => true, 'message' => 'Session expired']);
            } else {
                last_activity();
                echo json_encode(['logged_out' => false, 'message' => 'Session active']);
            }
           
        } catch(Exception $e) {
            echo json_encode(['logged_out' => false, 'error' => $e->getMessage()]);
        }
    ?>
   

This check_session.php file checks the validity of the user's session and manages auto-logout. First, the session is started and included in common functions, then the response format is set to JSON so that the front-end can easily parse it. The autologout() function checks whether the session has expired or is active; if it has expired, it returns JSON with logged_out: true and message: Session expired, and if it is active, the session timestamp is updated using last_activity() and it returns JSON with logged_out: false and message: Session active. If any exception occurs, a JSON response with an error message is sent. This is how this file works for real-time session monitoring and automatic logout.



    1config\common_function.php
    <?php
        /**
         * Check if user is logged in, redirect to dashboard if yes
         */
        function emailSet() {
            try {
                if(isset($_SESSION['emailID']) && !empty($_SESSION['emailID'])) {
                    header('location:../3view/pages/dashboard.php');
                    exit();
                }
            } catch(Exception $e) {
                error_log("emailSet Error: " . $e->getMessage());
            }
        }

        /**
         * Check if user is NOT logged in, redirect to login if not
         */
        function emailNotSet() {
            try {
                if(!isset($_SESSION['emailID']) || empty($_SESSION['emailID'])) {
                    $_SESSION['warning'] = 'Please login to access this page';
                    header('location:../../3view/login.php');
                    exit();
                }
            } catch(Exception $e) {
                error_log("emailNotSet Error: " . $e->getMessage());
                header('location:../../3view/login.php');
                exit();
            }
        }

        /**
         * Update last activity time
         */
        function last_activity() {
            $_SESSION['last_activity'] = time();
        }

        /**
         * Auto logout after inactivity
         */
        function autologout() {
            try {
                if(isset($_SESSION['last_activity']) && !empty($_SESSION['last_activity'])) {
                    $inactive_time = 1800; // 30 minutes
                    if((time() - $_SESSION['last_activity']) > $inactive_time) {
                        session_unset();
                        session_destroy();
                        return true;
                    }
                }
                return false;
            } catch(Exception $e) {
                error_log("autologout Error: " . $e->getMessage());
                return false;
            }
        }

        /**
         * Set toast message
         */
        function setToast($type, $message) {
            $_SESSION['toast_type'] = $type;
            $_SESSION['toast_message'] = $message;
        }

        /**
         * Get and clear toast message
         */
        function getToast() {
            if(isset($_SESSION['toast_type']) && isset($_SESSION['toast_message'])) {
                $toast = [
                    'type' => $_SESSION['toast_type'],
                    'message' => $_SESSION['toast_message']
                ];
                unset($_SESSION['toast_type']);
                unset($_SESSION['toast_message']);
                return $toast;
            }
            return null;
        }
    ?>


This common_function.php file provides several reusable functions used for session and notification management within the login system. A function-by-function explanation is as follows:

emailSet(): This function checks if a user is already logged in by looking for $_SESSION['emailID']. If a session exists, it automatically redirects the user to the dashboard to prevent them from accessing the login or registration pages again.

emailNotSet(): Conversely to emailSet(), this function checks if the user is NOT logged in. If no active session is found, it sets a warning message and redirects the user to the login page, ensuring that only logged-in users can access protected pages.

last_activity(): This updates the session variable $_SESSION['last_activity'] with the current timestamp. This is used to track user activity for session timeout purposes.

autologout(): This function automatically logs out a user if they have been inactive for a specified period (30 minutes in your case). It compares the current time to $_SESSION['last_activity'], and if the inactivity exceeds the limit, it destroys the session and returns true; otherwise, it returns false.

setToast($type, $message): This function stores a "toast" notification in session variables, including the type (success, error, warning) and the message. These are later used to display notifications to the user on the frontend.

getToast(): This function retrieves the toast message stored by setToast() and removes it from the session. It returns the message and type as an array, or null if no toast is set. This allows notifications to be displayed only once. These functions collectively handle session control, auto-logout, and user notifications in a structured manner, ensuring security and a seamless user experience.

Conclusion

Creating a modern PHP login and registration system with Tailwind CSS is a significant milestone for every web project. Through this project, you learned how the different layers of web development—frontend, backend, and frontend—combine to create a secure, user-friendly environment.

By setting up a credit card, you learned how to securely create and manage your user credentials. Then, with the Tailwind CSS-SAN operator login and registration forum, you created a beautiful and valid labeler. The backend logic—built using PHP, MySQL, and secure password hashing—ensures user data is safe, secure, and durable.

Additionally, integration evaluation and security of Seventeen management, auto-logout, and toast detergent are achieved, providing a professional experience with real-world tools. These techniques are not only practical but also the most effective in modern web development.

By following this guide, you should now understand how to:

  1. Build a functional system using PHP and MySQL.
  2. Use password_hash() and password_verify() for secure login management.
  3. Protect user sessions securely with session_start(), session_destroy(), and Activity Journeys.
  4. Implement a clean, responsive setup using Tailwind CSS.
  5. View portable user documentation via ToastToilet.

With this foundation, you're now ready to expand your system—passwords, email verification, user roles, and a two-factor credential database.

This project not only teaches you how to log in and log out—it also teaches you how to scale like Velcro, ensuring your journey is both secure and scalable.

Post a Comment

Previous Post Next Post