The registration and login system is a crucial step for all kinds of websites as a security measure as well as creating a database. You can make a Login Form from a basic to an advanced structure and design using HTML and CSS. But you need PHP to add security, validate the login details, and process information on the form. In this blog, we will learn how to make a secure Login System and registration form using PHP and MySQL. It will guide you step-by-step to create a complete working system that securely connects files, manages user redirection, and diligently stores user details in the database. We implement the best practices and code with the help of XAMPP.
Table of Contents:
Pre-requisites
Before we dive into the code implementation and step-by-step guide for creating a login system and registration system, it would be helpful to have all the necessary technological requirements and environment setup installed and ready. Here is the compiled list of all the tools you need to successfully create a login and registration system.
- XAMPP: This is the most important installation. XAMPP bundles Apache, MySQL, MariaDB, PHP, and phpMyAdmin, eliminating the need to install them separately. These applications are required to run the system smoothly without errors. If your system doesn’t have XAMPP, you can follow these steps to install XAMPP on your local system. XAMPP is a package of back-end technologies that acts as a local web server to run and test web applications. It acts as a web server on your local computer and runs the code.
- Basic HTML & CSS Knowledge is needed to design the frontend of the various website pages.
- MySQL: MySQL is a relational database management system (RDBMS). It will be used to create a database and store the details of registered users. These details will be fetched later to authenticate the login inputs and grant access. If you are using XAMPP, then you don’t have to worry about the installation. You can access the MySQL services through phpMyAdmin.
- Apache: Apache is the web server component in XAMPP. It handles HTTP requests and serves your PHP files to the browser.
- PHP: PHP (Hypertext Preprocessor) is a server-side scripting language used to build dynamic web applications. In this project, PHP handles form submissions, interacts with the database, and implements business logic such as user authentication.
- Any text editor installed on the local system, such as VS Code, Sublime Text, or any that you are comfortable with.
File Structure of the Project
The file structure of the project that this blog follows is as written below. You can have your own structure using the following one as a reference.
The Registration System Folder
The registration system has two files: Registration.php and config.php.
- Config.php: This file contains the connection parameters. This is the file that is responsible for the connection of all the PHP scripts of the login form with the Database.
- Registration.php: This file contains the HTML code for the front end of the form, including input fields to collect the user details. It also links to the global style.css sheet for the styling of the Registration page. It also has the PHP code to submit the form inputs, validate them, and finally insert them into the SQL Database.
The Login System Folder
The login system is made up of four PHP scripts: authentication.php, login_page.php, logout.php, and dashboard.php.
- Login_page.php: It contains the HTML structure for the login form. It also holds PHP code to display any authentication error messages. This file is responsible for providing the user interface for logging in and sending login credentials for processing.
- Authentication.php: It is a pure PHP code file. It includes config.php for database access. It is responsible for securely validating user login attempts and establishing a user session. It also manages redirections based on authentication success or failure.
- Dashboard.php: This file contains HTML code to display a user’s profile and a welcome message. This page is only accessible to logged-in users. It fetches the details of the user who is logging in and dynamically displays their profile details.
- Logout.php: This file contains PHP code for session management. Its purpose is to securely destroy a user’s active session and redirect them to the login page.
Images Folder
It contains only the company’s logo image file in this example. If you have other images in your project, add them to this folder and give their relative path in the src parameter of the <img> tag.
CSS Folder
This folder will contain the style sheet of the system. All the webpages follow a basic style for the headers, font family, and colour theme. All the common styles will be stored in the style.css file.
Code: style.css
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
background-color: #f8f8f8; /* Light gray background */
display: flex;
flex-direction: column; /* For header at top and content below */
min-height: 100vh; /* Full viewport height */
}
.container {
flex-grow: 1; /* Allows container to take available space */
display: flex;
justify-content: center;
align-items: flex-start; /* Align to start, not center, to push form up a bit */
padding: 40px 20px;
}
/* Header Styling */
.header {
background-color: #57147d; /* Intellipaat Purple */
color: white;
padding: 15px 40px;
display: flex;
justify-content: space-between;
align-items: center;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}
.header-title {
font-size: 1.8em;
font-weight: bold;
margin-right: auto; /* Pushes logo to right */
margin-left: 20px; /* Space between logo and title */
}
.intellipaat-logo {
height: 40px; /* Adjust as needed */
width: auto;
display: block; /* Removes extra space below image */
}
/* Form Section Styling */
.form-section {
background-color: white;
padding: 40px 50px;
border-radius: 8px;
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
width: 100%;
max-width: 800px; /* Adjust based on desired width */
display: flex;
flex-direction: column;
}
.form-section h2 {
text-align: left;
color: #333;
font-size: 2em;
margin-bottom: 30px;
}
/* Form Layout */
.registration-form {
display: flex;
flex-direction: column;
gap: 20px; /* Space between rows/groups */
}
.form-row {
display: flex;
gap: 30px; /* Space between form groups in a row */
width: 100%;
}
.form-group {
flex: 1; /* Each form group takes equal space in a row */
display: flex;
flex-direction: column;
}
.form-group label {
margin-bottom: 8px;
color: #666;
font-weight: bold;
font-size: 0.9em;
}
.form-group input[type="text"],
.form-group input[type="email"],
.form-group input[type="password"],
.form-group input[type="tel"],
.form-group select {
width: 100%;
padding: 12px;
border: 1px solid #ccc;
border-radius: 5px;
font-size: 1em;
box-sizing: border-box; /* Include padding in width */
}
.form-group input:focus,
.form-group select:focus {
border-color: #57147d; /* Highlight on focus */
outline: none;
box-shadow: 0 0 5px rgba(87, 20, 125, 0.2); /* Soft shadow on focus */
}
/* Required field asterisk */
.required {
color: #ff0000; /* Red color for asterisk */
margin-left: 2px;
}
/* Checkbox group styling */
.checkbox-group {
flex-direction: row; /* Align checkbox and label horizontally */
align-items: center;
gap: 10px; /* Space between checkbox and label */
margin-top: 10px;
}
.checkbox-group input[type="checkbox"] {
width: auto; /* Override default input width */
}
.checkbox-group label {
font-weight: normal;
font-size: 0.9em;
color: #333;
}
.checkbox-group a {
color: #57147d; /* Intellipaat purple for links */
text-decoration: none;
}
.checkbox-group a:hover {
text-decoration: underline;
}
/* Register Button */
.register-button {
background-color: #ff8c00; /* Intellipaat Orange */
color: white;
padding: 15px 25px;
border: none;
border-radius: 5px;
font-size: 1.1em;
font-weight: bold;
cursor: pointer;
transition: background-color 0.3s ease;
width: fit-content; /* Button width adjusts to content */
align-self: flex-start; /* Align button to left */
margin-top: 20px;
}
.register-button:hover {
background-color: #e07b00; /* Slightly darker orange on hover */
}
/* Responsive Design for smaller screens */
@media (max-width: 768px) {
.header {
flex-direction: column;
text-align: center;
padding: 15px 20px;
}
.header-title {
margin-top: 10px;
margin-left: 0;
margin-right: 0;
}
.form-section {
padding: 30px;
margin: 20px; /* Add some margin on smaller screens */
}
.form-row {
flex-direction: column; /* Stack form groups vertically */
gap: 20px;
}
.register-button {
width: 100%; /* Full width button on small screens */
align-self: center; /* Center button */
}
}
@media (max-width: 480px) {
.form-section {
padding: 20px;
}
.form-section h2 {
font-size: 1.8em;
margin-bottom: 20px;
}
}
How to create a Registration System using PHP?
Let us look at the complete code implementation of a basic registration system before moving on to the login system.
Step 1: Set Up the Environment
- You first need to open the XAMPP folder that is located in the C: folder. If you have downloaded it somewhere else, navigate to that folder.
- In that folder, click on the xampp-control.exe and start the XAMPP Control Panel.
- Start the Apache and MySQL services from the XAMPP Control Panel. They should turn Green. If they turn yellow or red, that means your services haven’t started yet.
Now your Environment is completely set up.
Warning: Ensure that Apache and MySQL are not blocked by a firewall.
Step 2: Create Registration.php File
- Navigate to the htdocs folder inside the XAMPP Folder in the C:.
- Create a folder where all your project files will reside in the future. You can name it as you wish.
Now, open this newly created folder in VS Code and create a registration.php file inside it. The key features of this file are,
- A major focus of this script is security. We’ll be using prepared statements to prevent SQL injection and password hashing, using the password_hash() to protect user passwords, ensuring they are never stored in plain text.
- It contains functions like $email_exists_err that provide clear error messages for invalid inputs, and handle cases, like already registered email addresses.
Some of the important functions that you need to change the values of, if you’re customizing your project:
- Using the “require_once __DIR__ . ‘/config.php’;” command, it includes the config.php file and secures the connection to MySQL.
- The SQL INSERT statement should have the correct name of your table and the schema of the database to store the details of the user.
- We use the password_hash($password, PASSWORD_DEFAULT) method to securely encrypt user passwords before storing them in the database. This is also important for password authentication.
- The condition strlen(trim($_POST[“password”])) < 6 sets the minimum number of characters required for a user’s password. You can change it according to the number of users you expect in your database.
- We have also used a Name Validation Regular Expression to validate character sets allowed in the name field, email field, and phone number field.
After coding and implementing everything, the final web page looks like this. Now open your browser and go to http://localhost/Login_Form_and_Registration_Form/Registration System/registration.php to test your form.
Code: registration.php
<?php
require_once __DIR__ . '/config.php'; // Connect to the database
// Initialize variables for form data and errors
$first_name = $last_name = $email = $password = $country = $phone = "";
$first_name_err = $last_name_err = $email_err = $password_err = $terms_err = $email_exists_err = "";
$registration_success = "";
// Check if the form was submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Validate First Name input
if (empty(trim($_POST["first_name"]))) {
$first_name_err = "Please enter your first name.";
} else {
$first_name = trim($_POST["first_name"]);
if (!preg_match("/^[a-zA-Z-' ]*$/", $first_name)) {
$first_name_err = "Only letters and white space allowed.";
}
}
// Validate Last Name input
if (empty(trim($_POST["last_name"]))) {
$last_name_err = "Please enter your last name.";
} else {
$last_name = trim($_POST["last_name"]);
if (!preg_match("/^[a-zA-Z-' ]*$/", $last_name)) {
$last_name_err = "Only letters and white space allowed.";
}
}
// Validate Email format and check if it's already registered
if (empty(trim($_POST["email"]))) {
$email_err = "Please enter your email address.";
} elseif (!filter_var(trim($_POST["email"]), FILTER_VALIDATE_EMAIL)) {
$email_err = "Please enter a valid email address.";
} else {
$email = trim($_POST["email"]);
// Check if the email already exists in the database
$sql = "SELECT id FROM registered_users WHERE email = ?";
if ($stmt = mysqli_prepare($link, $sql)) {
mysqli_stmt_bind_param($stmt, "s", $param_email);
$param_email = $email;
if (mysqli_stmt_execute($stmt)) {
mysqli_stmt_store_result($stmt);
if (mysqli_stmt_num_rows($stmt) == 1) {
$email_exists_err = "This email is already registered.";
}
} else {
error_log("Error checking email existence: " . mysqli_stmt_error($stmt));
echo "Oops! Something went wrong. Please try again later.";
}
mysqli_stmt_close($stmt);
} else {
error_log("Error preparing email check statement: " . mysqli_error($link));
echo "Oops! Something went wrong. Please try again later.";
}
}
// Validate Password input
if (empty(trim($_POST["password"]))) {
$password_err = "Please enter a password.";
} elseif (strlen(trim($_POST["password"])) < 6) {
$password_err = "Password must have at least 6 characters.";
} else {
$password = trim($_POST["password"]);
}
// Check if the user accepted the terms
if (!isset($_POST["terms"])) {
$terms_err = "You must agree to the Terms of Use & Privacy Policy.";
}
// Optional fields: country and phone
$country = $_POST["country"] ?? '';
$phone = trim($_POST["phone"] ?? '');
// Insert data into database only if there are no errors
if (empty($first_name_err) && empty($last_name_err) && empty($email_err) && empty($password_err) && empty($terms_err) && empty($email_exists_err)) {
// Insert user into database
$sql = "INSERT INTO registered_users (first_name, last_name, email, password, country, phone) VALUES (?, ?, ?, ?, ?, ?)";
if ($stmt = mysqli_prepare($link, $sql)) {
mysqli_stmt_bind_param($stmt, "ssssss", $param_first_name, $param_last_name, $param_email, $param_password, $param_country, $param_phone);
// Assign values to parameters
$param_first_name = $first_name;
$param_last_name = $last_name;
$param_email = $email;
// Secure password before storing it in the database
$param_password = password_hash($password, PASSWORD_DEFAULT);
$param_country = $country;
$param_phone = $phone;
if (mysqli_stmt_execute($stmt)) {
$registration_success = "Registration successful! You can now log in.";
// Clear input values after successful registration
$first_name = $last_name = $email = $password = $country = $phone = "";
} else {
error_log("MySQLi Insert Error: " . mysqli_stmt_error($stmt));
echo "Error during registration. Please try again.";
}
mysqli_stmt_close($stmt);
} else {
error_log("MySQLi Prepare Error: " . mysqli_error($link));
echo "Error preparing registration statement. Please try again.";
}
}
// Close the database connection
mysqli_close($link);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sign Up - Intellipaat</title>
<link rel="stylesheet" href="../css/style.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
</head>
<body>
<header class="header">
<div class="logo-container">
<img src="../images/intellipaat_logo.png" alt="Intellipaat Logo" class="intellipaat-logo">
</div>
</header>
<div class="container">
<div class="form-section">
<h2>Sign Up</h2>
<?php
// Display success message if registration was successful
if (!empty($registration_success)) {
echo '<div class="success-msg">' . $registration_success . '</div>';
}
?>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="POST" class="registration-form">
<div class="form-row">
<div class="form-group <?php echo (!empty($first_name_err)) ? 'has-error' : ''; ?>">
<label for="first_name">First Name</label>
<input type="text" id="first_name" name="first_name" value="<?php echo htmlspecialchars($first_name); ?>" required>
<span class="help-block"><?php echo $first_name_err; ?></span>
</div>
<div class="form-group <?php echo (!empty($last_name_err)) ? 'has-error' : ''; ?>">
<label for="last_name">Last Name</label>
<input type="text" id="last_name" name="last_name" value="<?php echo htmlspecialchars($last_name); ?>" required>
<span class="help-block"><?php echo $last_name_err; ?></span>
</div>
</div>
<div class="form-row">
<div class="form-group <?php echo (!empty($email_err) || !empty($email_exists_err)) ? 'has-error' : ''; ?>">
<label for="email">Email address <span class="required">*</span></label>
<input type="email" id="email" name="email" value="<?php echo htmlspecialchars($email); ?>" required>
<span class="help-block"><?php echo $email_err; ?><?php echo $email_exists_err; ?></span>
</div>
<div class="form-group <?php echo (!empty($password_err)) ? 'has-error' : ''; ?>">
<label for="password">Password <span class="required">*</span></label>
<input type="password" id="password" name="password" required>
<span class="help-block"><?php echo $password_err; ?></span>
</div>
</div>
<div class="form-row">
<div class="form-group">
<label for="country">Country</label>
<select id="country" name="country">
<option value="">Select a country...</option>
<option value="India" <?php echo ($country == 'India') ? 'selected' : ''; ?>>India</option>
<option value="USA" <?php echo ($country == 'USA') ? 'selected' : ''; ?>>USA</option>
<option value="UK" <?php echo ($country == 'UK') ? 'selected' : ''; ?>>United Kingdom</option>
</select>
</div>
<div class="form-group">
<label for="phone">Phone</label>
<input type="tel" id="phone" name="phone" value="<?php echo htmlspecialchars($phone); ?>">
</div>
</div>
<div class="form-group checkbox-group <?php echo (!empty($terms_err)) ? 'has-error' : ''; ?>">
<input type="checkbox" id="terms" name="terms" <?php echo (isset($_POST['terms'])) ? 'checked' : ''; ?> required>
<label for="terms">By providing your contact details, you agree to our <a href="#">Terms of Use</a> & <a href="#">Privacy Policy</a></label>
<span class="help-block"><?php echo $terms_err; ?></span>
</div>
<button type="submit" class="register-button">Register</button>
</form>
<p class="form-footer-link">Already have an account? <a href="../Login System/login_page.php">Login here</a></p>
</div>
</div>
</body>
</html>
Step 3: Create a Database Table
To store the details of the user, we will create a table in MySQL. Based on the Registration page, the table schema we will follow is:
CREATE TABLE registered_users (
id INT AUTO_INCREMENT PRIMARY KEY,
first_name VARCHAR(50) NOT NULL,
last_name VARCHAR(50) NOT NULL,
email VARCHAR(100) NOT NULL UNIQUE,
password VARCHAR(255) NOT NULL,
country VARCHAR(50),
phone VARCHAR(15)
);
- In the left-hand side menu bar, select the New option, and a create database dashboard will open. Name your database and click on Create.
- Now, you have to create a table. Give the number of columns you want to have, and again click on Create. The structure of the table followed in this blog is as follows:
- A structure dashboard will open. This page will be used to name the columns, set the data types, length constraints, attributes and many other things to define the fields.
The final table structure will look like this.
Now we have to connect this database to the web page. We will do this in the config.php file.
Step 4: Create a config.php File to connect to MySQL
The config.php file is the central configuration file for your entire system. Its primary role is to establish and manage the connection to your MySQL database.
Some of the important values that you must change if you’re customizing your project:
- DB_SERVER: It specifies the hostname or IP address where your MySQL database server is running. You must change the value ‘localhost’ if your database is hosted on a different server, for example, a cloud database.
- DB_USERNAME: This function holds the username that your PHP application will use to authenticate with the MySQL database. You must change ‘root’ to your actual database username.
- DB_NAME: This constant specifies the name of the particular database your application interacts with. You must change user_details to your database name.
The code is as follows:
config.php
<?php
/* Database credentials. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', ''); // Default XAMPP MySQL root password is empty
define('DB_NAME', 'user_details');
/* Attempt to connect to MySQL database */
$link = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
?>
You can check whether a successful connection was made or not by typing http://localhost/your_foldername/config.php in the URL area. If the connection is successful, there would be a blank page; otherwise, it would display an error message.
Working of the Registration System
Now that we have coded all these basic elements and added all the connection functions, your registration system in PHP has been created successfully and will work smoothly.
You can see that the saved password in the database table was not in plain text.
Get 100% Hike!
Master Most in Demand Skills Now!
How to create a Login System using PHP?
Once the registration system is complete, we can move forward with the Login system using PHP.
A basic login system will have a login page, a logout page, a dashboard that opens once the user has logged in, and finally, an authentication page that takes care of validating and authenticating the user trying to log in.
Step 1: Create a Login Form
Using HTML, create a Login page with input fields for email and password. These fields will be later processed for authentication.
The PHP will be responsible for collecting the input values and supplying them to authentication.php to process and validate against the database values.
Some other key functions used in this PHP script are:
- session_start(): It is used to start or resume a PHP session. This allows the application to store temporary user data. For example, the $_SESSION[‘login_error’] variable is used to display authentication errors that might come from authentication.php after a redirect.
Note: A PHP session allows the server to remember a user across multiple pages. When you log in, PHP creates a session to store user details like email and name until the user logs out.
- HTTP Request Method: Check using if ($_SERVER[“REQUEST_METHOD”] == “POST”). POST is used here because it shares the form data securely, without exposing it in the URL.
- “require_once __DIR__ . ‘/authentication.php’;”: This command includes the authentication.php file, which contains the core logic for verifying the submitted email and password against your database records.
- Form Action: The action attribute of the HTML<form> tag is set to htmlspecialchars($_SERVER[“PHP_SELF”]). This makes the form submit back to the same login_page.php script for processing.
- At the bottom of the login page, an HTML anchor tag is used to link to ../Registration System/registration.php. This allows easy navigation to the sign-up page.
After the code implementation, the login page will look like this.
Code: login_page.php
<?php
// Start a session so we can store messages or user data temporarily
session_start();
// Initialize form input and error message variables
$email = $password = "";
$email_err = $password_err = "";
$login_err = ""; // A general error message if login fails
// Check if a login error message was set by authentication.php
if (isset($_SESSION['login_error'])) {
$login_err = $_SESSION['login_error']; // Retrieve the message
unset($_SESSION['login_error']); // Remove it after displaying (flash message behavior)
}
// When the form is submitted using POST
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Validate Email field
if (empty(trim($_POST["email"]))) {
$email_err = "Please enter your email.";
} else {
$email = trim($_POST["email"]);
}
// Validate Password field
if (empty(trim($_POST["password"]))) {
$password_err = "Please enter your password.";
} else {
$password = trim($_POST["password"]);
}
// If there are no input errors, forward the request to authentication.php
if (empty($email_err) && empty($password_err)) {
require_once __DIR__ . '/authentication.php';
}
}
?><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login - Intellipaat</title>
<!-- Main stylesheet for consistent styling -->
<link rel="stylesheet" href="../css/style.css">
<!-- Font Awesome icons (optional but useful for UI icons) -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
</head>
<body>
<!-- Header with company logo -->
<header class="header">
<div class="logo-container">
<img src="../images/intellipaat_logo.png" alt="Intellipaat Logo" class="intellipaat-logo">
</div>
</header>
<!-- Main login form container -->
<div class="container">
<div class="form-section">
<h2>Login</h2>
<!-- Show login error message if it exists -->
<?php
if (!empty($login_err)) {
echo '<div class="error-msg">' . $login_err . '</div>';
}
?>
<!-- Login form starts -->
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="POST" class="login-form">
<!-- Email Input -->
<div class="form-group <?php echo (!empty($email_err)) ? 'has-error' : ''; ?>">
<label for="email">Email address</label>
<input type="email" id="email" name="email" value="<?php echo htmlspecialchars($email); ?>" required>
<span class="help-block"><?php echo $email_err; ?></span>
</div>
<!-- Password Input -->
<div class="form-group <?php echo (!empty($password_err)) ? 'has-error' : ''; ?>">
<label for="password">Password</label>
<input type="password" id="password" name="password" required>
<span class="help-block"><?php echo $password_err; ?></span>
</div>
<!-- Submit Button -->
<button type="submit" class="register-button">Login</button>
</form>
<!-- Navigation to registration -->
<p class="form-footer-link">
Don't have an account?
<a href="../Registration System/registration.php">Sign Up here</a>.
</p>
</div>
</div>
</body>
</html>
Step 2: Authentication
Once the user inputs their details in the login form, PHP stores these details in variables and sends them to authentication.php file. It is then responsible for processing, matching it to the database, and authenticating it. It is done after the session has started.
The file includes the config.php to establish the connection with the SQL database.
Code: authentication.php
<?php
// Ensure this file is accessed through a proper POST request and a session is active
if (session_status() == PHP_SESSION_NONE) {
session_start(); // Start the session if it hasn't been started
}
// Include the database configuration file
// authentication.php is in 'Login System/', and config.php is in '../Registration System/'
require_once __DIR__ . '/../Registration System/config.php';
// Check that form inputs are set; this is a basic check already handled in login_page.php
if (isset($_POST["email"]) && isset($_POST["password"])) {
// Sanitize and assign form inputs
$email = trim($_POST["email"]);
$password = trim($_POST["password"]);
$login_err = ""; // Initialize an error message variable
// Prepare an SQL query to retrieve the user by email
$sql = "SELECT id, first_name, email, password FROM registered_users WHERE email = ?";
if ($stmt = mysqli_prepare($link, $sql)) {
// Bind the email parameter to the SQL query
mysqli_stmt_bind_param($stmt, "s", $param_email);
$param_email = $email;
// Execute the prepared statement
if (mysqli_stmt_execute($stmt)) {
// Store the result to check if the email exists
mysqli_stmt_store_result($stmt);
// If the email exists, proceed with password verification
if (mysqli_stmt_num_rows($stmt) == 1) {
// Bind the result columns to PHP variables
mysqli_stmt_bind_result($stmt, $id, $first_name_db, $email_db, $hashed_password);
if (mysqli_stmt_fetch($stmt)) {
// Verify the submitted password against the hashed password in the database
if (password_verify($password, $hashed_password)) {
// Password is correct; regenerate session ID to prevent session fixation attacks
session_regenerate_id(true);
// Store user information in session variables
$_SESSION["loggedin"] = true;
$_SESSION["id"] = $id;
$_SESSION["email"] = $email_db;
$_SESSION["first_name"] = $first_name_db;
// Redirect the user to the dashboard page
header("location: dashboard.php");
exit();
} else {
// Password is incorrect
$login_err = "Invalid email or password.";
}
}
} else {
// Email does not exist in the database
$login_err = "Invalid email or password.";
}
} else {
// Failed to execute the prepared statement
$login_err = "An error occurred while processing your request. Please try again later.";
error_log("Authentication Error: mysqli_stmt_execute failed: " . mysqli_stmt_error($stmt));
}
// Close the prepared statement
mysqli_stmt_close($stmt);
} else {
// Failed to prepare the SQL statement
$login_err = "An error occurred while processing your request. Please try again later.";
error_log("Authentication Error: mysqli_prepare failed: " . mysqli_error($link));
}
// If authentication failed, store the error message in the session and redirect to login page
$_SESSION['login_error'] = $login_err;
header("location: login_page.php");
exit();
} else {
// If accessed directly without POST data, redirect to the login page
header("location: login_page.php");
exit();
}
// Close the database connection
mysqli_close($link);
?>
Step 3: Create a Dashboard and Profile Section
The dashboard.php file will display only for registered users. Once the input details in the login form have been successfully validated, the user is redirected to the dashboard.php file.
This file dynamically fills up with the details of the logged-in users using the mysqli_stmt_bind_result() function and mysqli_stmt_fetch().
- The mysqli_stmt_bind_result($stmt, $first_name, $last_name, $email, $country, $phone) function is used to bind PHP variables to the columns in the database table.
- After variables are bound, the mysqli_stmt_fetch() function fetches the data from the database and populates the bound variables with the retrieved values.
After the code implementation, the page will look like this:
Code: dashboard.php
<?php
// Start the session to access user data stored during login
session_start();
// Check if the user is logged in; if not, redirect to the login page
if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true) {
header("location: login_page.php");
exit;
}
// Include the database configuration file to fetch user details
// dashboard.php is in 'Login System/', so go up one level to reach config.php in 'Registration System/'
require_once __DIR__ . '/../Registration System/config.php';
$user_details = []; // Initialize an array to store fetched user information
// If user ID is available in the session, retrieve user data from the database
if (isset($_SESSION["id"])) {
$sql = "SELECT first_name, last_name, email, country, phone FROM registered_users WHERE id = ?";
if ($stmt = mysqli_prepare($link, $sql)) {
mysqli_stmt_bind_param($stmt, "i", $param_id);
$param_id = $_SESSION["id"];
if (mysqli_stmt_execute($stmt)) {
mysqli_stmt_store_result($stmt);
// If one matching record is found, bind the result and populate the array
if (mysqli_stmt_num_rows($stmt) == 1) {
mysqli_stmt_bind_result($stmt, $first_name, $last_name, $email, $country, $phone);
if (mysqli_stmt_fetch($stmt)) {
$user_details = [
'first_name' => $first_name,
'last_name' => $last_name,
'email' => $email,
'country' => $country,
'phone' => $phone
];
}
}
} else {
// Log any errors that occur during execution
error_log("Dashboard: Error fetching user details: " . mysqli_stmt_error($stmt));
}
mysqli_stmt_close($stmt);
} else {
// Log if statement preparation fails
error_log("Dashboard: Error preparing user details statement: " . mysqli_error($link));
}
// Close the database connection after use
mysqli_close($link);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dashboard - Intellipaat</title>
<link rel="stylesheet" href="../css/style.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
<style>
/* Additional styles for the dashboard and profile section */
.dashboard-container {
max-width: 900px;
margin: 50px auto;
background-color: #fff;
padding: 40px;
border-radius: 8px;
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
text-align: center;
}
.dashboard-container h2 {
color: #333;
margin-bottom: 25px;
font-size: 2em;
}
.welcome-message {
font-size: 1.5em;
color: #57147d; /* Intellipaat purple */
margin-bottom: 30px;
}
.profile-section {
background-color: #f9f9f9;
border: 1px solid #ddd;
border-radius: 8px;
padding: 30px;
margin-top: 30px;
text-align: left;
}
.profile-section h3 {
color: #57147d;
margin-bottom: 20px;
font-size: 1.6em;
border-bottom: 2px solid #eee;
padding-bottom: 10px;
}
.profile-detail {
margin-bottom: 15px;
font-size: 1.1em;
color: #555;
}
.profile-detail strong {
display: inline-block;
width: 120px; /* Align labels */
color: #333;
}
.dashboard-links {
margin-top: 40px;
display: flex;
justify-content: center;
gap: 20px;
}
.dashboard-links a {
background-color: #57147d;
color: white;
padding: 12px 25px;
border-radius: 5px;
text-decoration: none;
font-weight: bold;
transition: background-color 0.3s ease;
}
.dashboard-links a:hover {
background-color: #43105f;
}
</style>
</head>
<body>
<header class="header">
<div class="logo-container">
<img src="../images/intellipaat_logo.png" alt="Intellipaat Logo" class="intellipaat-logo">
</div>
</header>
<div class="dashboard-container">
<h2>Dashboard</h2>
<p class="welcome-message">Welcome, <b><?php echo htmlspecialchars($_SESSION["first_name"]); ?></b> to Intellipaat!</p>
<div class="profile-section">
<h3>Your Profile Details</h3>
<?php if (!empty($user_details)): ?>
<div class="profile-detail">
<strong>First Name:</strong> <?php echo htmlspecialchars($user_details['first_name']); ?>
</div>
<div class="profile-detail">
<strong>Last Name:</strong> <?php echo htmlspecialchars($user_details['last_name']); ?>
</div>
<div class="profile-detail">
<strong>Email:</strong> <?php echo htmlspecialchars($user_details['email']); ?>
</div>
<div class="profile-detail">
<strong>Country:</strong> <?php echo htmlspecialchars($user_details['country']); ?>
</div>
<div class="profile-detail">
<strong>Phone:</strong> <?php echo htmlspecialchars($user_details['phone']); ?>
</div>
<?php else: ?>
<p>No profile details found or an error occurred.</p>
<?php endif; ?>
</div>
<div class="dashboard-links">
<a href="reset_password.php">Reset Your Password</a>
<a href="logout.php">Sign Out of Your Account</a>
</div>
</div>
</body>
</html>
Step 4: Create a Logout File
This file will be responsible for destroying a session and allowing the user to securely log out from the website. When you click on the “Sign out of your Account” button, this file is invoked. It logs the user out and redirects them to the login page.
Code: logout.php
<?php
// Initialize the session
session_start();
// Unset all of the session variables
$_SESSION = array();
// Destroy the session.
session_destroy();
// Redirect to login page
// logout.php is in 'Login System/', and login_page.php is also in 'Login System/'.
// So, the direct file name is correct for the redirect.
header("location: login_page.php");
exit;
?>
Working of the Login System
With this, our login system in PHP has also been created successfully. Now let us take the same email and password that were registered earlier and try to log in to the system.
Explanation: Using the email and password with which we registered before, we tried to log in. PHP authenticated the credentials, and the dashboard was opened, dynamically populated with the credentials. When we clicked on “Sign Out of Your Account,” we were redirected to the login page, destroying the current session.
This GitHub repository includes all the PHP files, SQL schema, CSS styles, and folder structure used in this tutorial so you can run the project on your own machine and customize it further.
Conclusion
Creating a registration and login system with PHP and MySQL is an important project for anyone wanting to understand how user authentication works on the web. In this tutorial, you have learned how to set up your environment, create registration and login forms, validate user input, connect to a database, and manage user sessions associated with logging in and out. Creating this type of system can be useful because it is the foundation of many other types of websites, ranging from e-learning platforms to online stores. This article helps you create a basic system. You can further customize it with password resetting, integrating the sign-up with Google feature, and more. The more you practice and enhance your application code, the more confident you will be in creating secure and user-friendly PHP applications.
How to create a Registration and Login System using PHP – FAQs
Q1. How to create registration form and login form in PHP?
You can build forms with HTML, CSS, handle submissions with PHP, and data storing with MySQL.
Q2. How to make a login system with PHP?
You can build it by creating a login form, verifying credentials using PHP and MySQL, starting a session, and redirecting users upon successful login.
Q3. How to create a login page in HTML?
You can use a simple HTML form with fields for username and password, and a submit button that sends data to a PHP script for processing.
Q4. How to connect login page with database?
You can connect it using PHP’s mysqli_connect() or PDO.
Q5. How to connect XAMPP with PHP?
You can connect by placing your PHP files in the htdocs folder of XAMPP, and accessing them via localhost in your browser.