Create a User Login/Signin System in PHP (Secure Authentication with Session)

A PHP login page is a page that contains an HTML form that users can fill in with their credentials to log into an application. It allows already registered users to access the restricted pages of the application based on their roles and permissions. Learn to create a simple and secure login system for PHP applications.

Create a User Login System in PHP

User authentication is a process that a web application implements to allow users who have already created accounts in the application to access restricted sections of the application. A user registration interface allows users to create new accounts, whereas a sign in interface allows users who have already created an account to log into the system. This post demonstrates how to authenticate users in PHP applications with a login/sign page.

 

How to Create a Login System with Session in PHP?

An authentication system in PHP mainly requires a database table, a login page with a form, and a server-side authentication script. The database table contains the user information of registered users for authentication, the login page allows users to enter their credentials, and the server-side script authenticates users against the submitted credentials. The implementation involves the following steps:

 

Step 1: Users Database Table

We need a database table that contains the records of registered users. We will use this table to authenticate users with their entered login details.

CREATE TABLE IF NOT EXISTS `users` (
`id` bigint NOT NULL AUTO_INCREMENT PRIMARY KEY,
`name` varchar(100) NOT NULL,
`email` varchar(150) NOT NULL UNIQUE,
`password` varchar(255) NOT NULL,
`token` varchar(255) DEFAULT NULL,
`is_verified` tinyint(1) DEFAULT '0'
);
 

Step 2: Application & Database Constants

Since we will need to connect to the database to retrieve user records, we define application and database constants in a separate file.

constants.php

<?php
define('BASE_URL', 'https://' . $_SERVER['SERVER_NAME']); // Application base URL
define('DB_HOST', 'DATABASE_HOST'); // Database host
define('DB_NAME', 'DATABASE_NAME'); // Database name
define('DB_USER', 'DATABASE_USERNAME'); // Username for database
define('DB_PASSWORD', 'DATABASE_PASSWORD'); // Password for database
 

Step 3: Login Form Page (PHP)

The first thing required for the implementation is a page containing an HTML form for users to enter their email/username and password to log in. The page has to have a conditional check at the top to check if the user is already logged in, then redirect the user to a dashboard page.

  • Start a session if the session has not started yet.
  • Add a condition to check if the user is already logged in or not. If the user is already logged in, redirect to the dashboard page.
  • Add an HTML form with fields for email and password.

index.php

<?php
if (!session_id()) {
session_start();
}

if (isset($_SESSION['user'])) {
header('Location: dashboard.php');
exit();
}
?>
<!DOCTYPE html>
<html>
<head>
<title>User Login System in PHP - Demo</title>
<meta content="text/html; charset=UTF-8" http-equiv="Content-Type"/>
<meta content="width=device-width, initial-scale=1, maximum-scale=1" name="viewport"/>
<link rel="stylesheet" href="css/style.css"/>
</head>
<body>
<section class="section py-4">
<div class="container">
<?php if (isset($_SESSION['flash'])) { ?>
<div class="alert alert-<?= isset($_SESSION['flash']['error']) ? 'red' : 'green'; ?>">
<?= $_SESSION['flash']['message']; ?>
</div>
<?php
unset($_SESSION['flash']);
} ?>

<form class="login-form" method="POST" action="authenticate.php">
<div class="mb-4">
<input type="email" name="email" class="form-control" placeholder="Email..." required="required"/>
</div>

<div class="mb-4">
<input type="password" name="password" class="form-control" placeholder="Password..." required="required"/>
</div>

<button type="submit" class="btn btn-green">
Login
</button>
</form>
</div>
</section>
</body>
</html>
 

Step 4: Authenticate Users in PHP (Server-Side)

When users enter their credentials and submit the login form, the form needs to be processed in a server-side authenticate.php authentication script. It will fetch records from the database for the entered username/email address and compare the entered password with the password in the database table using PHP's password_verify function. The script redirects the user to a dashboard page after successful authentication. The following is an explanation of the script code:

  • Start a session if the session has not already started.
  • Sanitize the user input array and check if the $_POST variable is not empty.
  • Connect to the database using the credentials from the constants.php file.
  • Prepare and execute an SQL statement to fetch the record with the submitted email address (use parameterized queries to avoid SQL injection attacks).
  • If a user with the provided email address does not exist in the database, redirect back with an alert message.
  • Check if the password the user entered matches the password in the database using the password_verify() function.
  • If the password does not match, redirect back with the wrong password message.
  • Set the user in the session and redirect the user to the dashboard page.

authenticate.php

<?php
if (!session_id()) {
session_start();
}

include_once 'constants.php';

// Sanitize input array
$post = filter_input_array(INPUT_POST);

if (!empty($post)) {
$db_connection = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) OR die(mysqli_connect_error());

// Prepare user data variables
$email = trim($post['email']);
$password = trim($post['password']);

if (!$stmt = mysqli_prepare($db_connection, 'SELECT * FROM users WHERE email = ? AND is_verified = 1')) {
die(mysqli_error($db_connection));
}

mysqli_stmt_bind_param($stmt, 's', $email);

mysqli_stmt_execute($stmt);

// If user with email does not exist, redirect back with proper alert message
if (!$result = mysqli_stmt_get_result($stmt)) {
$_SESSION['flash'] = [
'error' => 1,
'message' => 'Entered email is not associated with any user.'
];

header('Location: index.php');
exit;
}

// Set user from MySQL result
$user = mysqli_fetch_assoc($result);

mysqli_stmt_close($stmt);

// If the entered password does not match, redirect back with an appropriate error message
if (!password_verify($password, $user['password'])) {
$_SESSION['flash'] = [
'error' => 1,
'message' => 'Wrong password! Please try again.'
];

header('Location: index.php');
exit;
}

$_SESSION['user'] = $user;

// Redirect back with success message
header('Location: dashboard.php');
exit;

}

// Fallback error message and redirect
$_SESSION['flash'] = [
'error' => 1,
'message' => 'Something went wrong! Please try again.'
];

header('Location: index.php');
exit;
 

Step 5: Dashboard Page

We need to redirect the users to some kind of dashboard or profile page after a successful authentication. This page and other pages that only logged-in users should access will have the same condition at the top. If a user tries to access this page directly, it will redirect the user to the login page. The page also has a logout link allowing users to log out from the application.

dashboard.php

<?php
if (!session_id()) {
session_start();
}

if (!isset($_SESSION['user'])) {
header('Location: index.php');
exit();
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Application Dashboard - Demo</title>
<meta content="text/html; charset=UTF-8" http-equiv="Content-Type"/>
<meta content="width=device-width, initial-scale=1, maximum-scale=1" name="viewport"/>
<link rel="stylesheet" href="css/style.css"/>
</head>
<body>
<section class="section py-4">
<div class="container">
<h1>Welcome!, <?= $_SESSION['user']['name']; ?></h1>
<div>This is a dummy dashboard.</div>
<div>
<a href="logout.php">Logout</a>
</div>
</div>
</section>
</body>
</html>
 

Step 6: Log Out Users in PHP

When the user clicks on the logout link, the user will be redirected to a script that destroys the user session and redirects the user back to the login page.

logout.php

<?php
if (!session_id()) {
session_start();
}

// Destroy session
session_unset(); // To free specific variable in the session
session_destroy(); // To destroy the complete session

// Redirect back to login page
header('Location: index.php');
exit();

A login page serves the purpose of user authentication and allows controlled access to an entire application or parts of it. We implemented a login system in PHP with dashboard and logout pages. We followed practices like session management, parameterized queries, and hash password checks with the password_verify() function. The code can be further modified to add a rate limit, CSRF protection, and regenerate the session ID after login.