Login Form in PHP (PHP Login Code)

PHP login form refers to an interface with a form where user can enter login details to access the authorized area of an application. Learn in this post how to login users in PHP with simple example code.

Login Form in PHP (PHP Login Code)

User authentication is a feature which a web application uses to authenticate registered users in order to protect certain sections of 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 few steps where a user interface with a PHP login form is first step. We create an HTML login form where users can enter their login details. After the login form is submitted we handle the form submission in server-side in PHP to authenticate users. The steps to implement login in PHP are as below:

 

Step 1: Database Table (Users)

Before starting with coding side, 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 database when retrieving user records for authentication. So we create a PHP constants file to defined 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 login details and then form will be submitted to server-side PHP script for authentication. The login form has a condition on top to check if user is not already logged in. If user is already logged in we redirect user to dashboard page.

  • Start a session if session is not started yet.
  • Add a condition to check if user is already logged or not. If user is already logged in redirect to 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 server-side authenticate.php script. This PHP login code will fetch records from database against entered email address. We check if the login details match with the database records we redirect user to dashboard page.

  • Start a session if session is not started.
  • Sanitize the user input array and check if $_POST variable is not empty.
  • Connect to database using the credentials from constants.php file.
  • Prepare and execute a SQL statement to fetch record with submitted email address.
  • If user with the provided email address does not exist in database, redirect back with alert message.
  • Check if password user entered matches the password in database using password_verify() function.
  • If password does not match, redirect back with wrong password message.
  • Set user in session and redirect user to 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 page. If user is not logged and tries to access this page, they will be redirected to login page. We also add a logout link which will allow users to logout from 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: Logout in PHP

When user clicks on logout link on dashboard page, we need a PHP logout code to destroy user session and redirect to 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 allows users to login to a web application using their login details.