Login Form in PHP (PHP Login Code)
A PHP login form refers to an interface with a form where users can enter login details to access the authorized area of an application. Learn in this post how to log in users in PHP with a simple example code.

User authentication is a feature that a web application uses to authenticate registered users to protect certain sections of the application and allow access only to registered users. This post will demonstrate how to authenticate users in PHP in simple steps with code examples.
How to Create a Login Form in PHP (Step-by-Step)
Authenticating users in PHP involves a few steps, where a user interface with a PHP login form is the first step. We create an HTML login form where users can enter their login details. After the login form is submitted, we handle the server-side form submission in PHP to authenticate users. The steps to implement login in PHP are as follows:
Step 1: Database Table (Users)
Before starting with the code, we need a database 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: Database Constants
We will also need some constants defined to connect to the database when retrieving user records for authentication. So we create a PHP constants file to define database configuration constants.
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 Interface (PHP)
Now we are ready to create a PHP login form where users can enter their login details, and then the form will be submitted to the server-side PHP script for authentication. The login form has a condition on top to check if the user is not already logged in. If the user is already logged in, we redirect the user to the 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>Login Form 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: Login Script PHP (Server-Side)
When the form is submitted to the server-side authenticate.php script. This PHP login code will fetch records from the database against the entered email address. We check if the login details match with the database records; we redirect the user to the dashboard page.
- Start a session if the session has not already started.
- Sanitize the user input array and check if the
$_POSTvariable is not empty. - Connect to the database using the credentials from the
constants.phpfile. - Prepare and execute an SQL statement to fetch the record with the submitted email address.
- 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 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 password entered does not match, return back with 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 create an interface for authenticated users with a login condition check on top of the page. If the user is not logged in and tries to access this page, they will be redirected to the login page. We also add a logout link that will allow users to log out of the application.
dashboard.php
<?php
if (!session_id()) {
session_start();
}
if (!isset($_SESSION['user'])) {
header('Location: index.php');
exit();
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Login 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 dummy dashboard.</div>
<div>
<a href="logout.php">Logout</a>
</div>
</div>
</section>
</body>
</html>
Step 6: Log Out in PHP
When the user clicks on the logout link on the dashboard page, we need a PHP logout code to destroy the user session and redirect to the login page.
logout.php
<?php
if (!session_id()) {
session_start();
}
// Destroy session
session_unset();
session_destroy();
// Redirect back to login page
header('Location: index.php');
exit();
We now have a working PHP login script with proper session management and parameterized queries that allow users to log in to a web application using their login details.