Create a Modern PHP Login and Registration System with Tailwind CSS
byRAYS CODING-
0
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.
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.
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.
name: Stores the user's full name. It is marked as NOT NULL to prevent registration without a name.
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.
mobile: Stores the user's mobile number. NOT NULL ensures that every user must provide a mobile number.
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.
created_at: Automatically records the time of user registration. This helps in tracking new users.
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.
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
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
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.
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.
thrownewException('No account found with this email');
}
} else {
thrownewException('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.
setToast('success', 'Registration successful! Welcome to Login System.');
header('location:../3view/pages/dashboard.php');
exit();
} else {
thrownewException('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.
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
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:
Build a functional system using PHP and MySQL.
Use password_hash() and password_verify() for secure login management.
Protect user sessions securely with session_start(), session_destroy(), and Activity Journeys.
Implement a clean, responsive setup using Tailwind CSS.
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.