Introduction
Password hashing, authentication, and authorization are essential parts of secure PHP applications. Password hashing protects stored passwords, authentication verifies a user’s identity, and authorization controls what an authenticated user can access. In this chapter, you will practise building secure registration, login, logout, role-based access, and protected pages using PHP and MySQL. Authentication and Authorization in PHP Practice Questions with Solutions to help you to understand the concepts.
Database Setup
Before starting the questions, create a database named auth_db and a table named users.
SQL Table Structure
CREATE DATABASE auth_db;
USE auth_db;
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(150) NOT NULL UNIQUE,
password VARCHAR(255) NOT NULL,
role ENUM('admin', 'user') NOT NULL DEFAULT 'user',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
The password column uses VARCHAR(255) because password hashes can be longer than ordinary passwords.
The role column stores whether a user is an administrator or a regular user.
Question 1: Generate a Secure Password Hash Using password_hash()
Problem Statement
Create a PHP program that generates a secure password hash using the password_hash() function. Display the original password and its generated hash.
PHP Solution
<?php
$password = "Rahul@123";
$hashedPassword = password_hash(
$password,
PASSWORD_DEFAULT
);
echo "Original Password: " . $password . "<br>";
echo "Hashed Password: " . $hashedPassword;
?>
Sample Output
Original Password: Rahul@123
Hashed Password:
$2y$10$... (hash output will vary)
Explanation
$passwordstores the original password.password_hash()converts the password into a secure hash.PASSWORD_DEFAULTtells PHP to use its current default password-hashing algorithm.$hashedPasswordstores the generated hash.
A password hash is not the same as ordinary encryption. It is designed to be one-way, meaning the original password cannot simply be recovered from the hash.
The generated hash may be different every time, even when the same password is used. This happens because PHP automatically generates a random salt.
Important: Never display or store the original password in a real registration application. This example displays it only to demonstrate the difference.
Concepts Covered
- Password hashing
password_hash()PASSWORD_DEFAULT- Secure password storage
- Password salt
Question 2: Verify a Password Using password_verify()
Problem Statement
Create a PHP program that generates a password hash and then checks whether a given password matches that hash.
PHP Solution
<?php
$password = "Rahul@123";
$hashedPassword = password_hash(
$password,
PASSWORD_DEFAULT
);
$loginPassword = "Rahul@123";
if (password_verify($loginPassword, $hashedPassword)) {
echo "Password is correct.";
} else {
echo "Invalid password.";
}
?>
Sample Output
Password is correct.
If $loginPassword is changed to "Rahul123", the output will be:
Invalid password.
Explanation
password_hash()generates a secure hash from the original password.$loginPasswordrepresents the password entered during login.password_verify()compares the entered password with the stored hash.- It returns
truewhen the password matches andfalsewhen it does not.
Notice that we do not decrypt the hash. PHP Authentication verifies the password by checking it against the stored hash.
Concepts Covered
password_verify()- Password verification
- Boolean return values
- Secure login verification
Question 3: Register a User with a Hashed Password Using MySQLi
Problem Statement
Create a PHP program that registers a new user in the MySQL database. Before saving the password, generate its secure hash using password_hash().
PHP Solution
<?php
$conn = new mysqli("localhost", "root", "", "auth_db");
if ($conn->connect_error) {
die("Database connection failed.");
}
$name = "Rahul";
$email = "rahul@gmail.com";
$password = "Rahul@123";
$hashedPassword = password_hash(
$password,
PASSWORD_DEFAULT
);
$sql = "INSERT INTO users (name, email, password)
VALUES (?, ?, ?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param(
"sss",
$name,
$email,
$hashedPassword
);
if ($stmt->execute()) {
echo "User registered successfully.";
} else {
echo "Unable to register user.";
}
$stmt->close();
$conn->close();
?>
Sample Output
User registered successfully.
Explanation
$name,$email, and$passwordstore the registration details.password_hash()generates a secure password hash.- The SQL query inserts the user’s details into the
userstable. prepare()creates a prepared SQL statement.bind_param()safely supplies the values.execute()runs the INSERT query.
The database stores the password hash instead of the original password.
Important: This example uses fixed values for practice. A real registration form must validate the name, email, and password before inserting the record. The email column is unique, so attempting to register an existing email will fail.
Concepts Covered
- User registration
- MySQLi database connection
- Password hashing
- INSERT query
- Prepared statements
- Unique email constraint
Question 4: Authenticate a User Using Email and Password
Problem Statement
Create a PHP Authentication program that checks whether a user exists in the database and verifies the entered password against the stored password hash.
PHP Solution
<?php
$conn = new mysqli("localhost", "root", "", "auth_db");
if ($conn->connect_error) {
die("Database connection failed.");
}
$email = "rahul@gmail.com";
$loginPassword = "Rahul@123";
$sql = "SELECT id, name, email, password, role
FROM users
WHERE email = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $email);
$stmt->execute();
$result = $stmt->get_result();
if ($user = $result->fetch_assoc()) {
if (password_verify(
$loginPassword,
$user['password']
)) {
echo "Login successful.<br>";
echo "Welcome, " .
htmlspecialchars($user['name']);
} else {
echo "Invalid email or password.";
}
} else {
echo "Invalid email or password.";
}
$stmt->close();
$conn->close();
?>
Sample Output
Login successful.
Welcome, Rahul
Explanation
The authentication process has two main steps.
Step 1: Find the user
SELECT id, name, email, password, role
FROM users
WHERE email = ?
This query searches for a user using their email address.
Step 2: Verify the password
password_verify($loginPassword, $user['password'])
This checks whether the entered password matches the stored password hash.
If both checks are successful, the user is authenticated.
The same generic error message is used for an unknown email and an incorrect password so that the application does not reveal which email addresses are registered.
Concepts Covered
- User authentication
- Email-based login
- Database search
password_verify()- Prepared statements
- Secure login messages
Question 5: Create a Login System Using PHP Sessions
Problem Statement
Create a PHP program that authenticates a user and stores their login information in a session. Once logged in, display a welcome message using the session data.
PHP Solution
<?php
session_start();
$conn = new mysqli("localhost", "root", "", "auth_db");
if ($conn->connect_error) {
die("Database connection failed.");
}
$email = "rahul@gmail.com";
$loginPassword = "Rahul@123";
$sql = "SELECT id, name, email, password, role
FROM users
WHERE email = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $email);
$stmt->execute();
$result = $stmt->get_result();
if ($user = $result->fetch_assoc()) {
if (password_verify(
$loginPassword,
$user['password']
)) {
session_regenerate_id(true);
$_SESSION['user_id'] = $user['id'];
$_SESSION['user_name'] = $user['name'];
$_SESSION['user_role'] = $user['role'];
echo "Login successful.<br>";
echo "Welcome, " .
htmlspecialchars($_SESSION['user_name']);
} else {
echo "Invalid email or password.";
}
} else {
echo "Invalid email or password.";
}
$stmt->close();
$conn->close();
?>
Sample Output
Login successful.
Welcome, Rahul
Explanation
A session allows PHP to remember information about a user across different page requests.
session_start()starts or resumes a session.session_regenerate_id(true)creates a new session ID after successful authentication.$_SESSION['user_id']stores the authenticated user’s ID.$_SESSION['user_name']stores the user’s name.$_SESSION['user_role']stores the user’s role.
After successful login, other PHP pages can use these session values to identify the logged-in user.
Important: In a real application, session cookies should use secure settings such as Secure, HttpOnly, and an appropriate SameSite policy. Configure these before starting the session.
Concepts Covered
- PHP Authentication sessions
session_start()- Session variables
- Session ID regeneration
- Login authentication
- Storing user information
Question 6: Create a Protected Dashboard Page
Problem Statement
Create a dashboard page that can only be accessed by logged-in users. If someone tries to open the dashboard without logging in, redirect them to the login page.
For this exercise, assume that the login process has already created the session.
PHP Solution
<?php
session_start();
if (!isset($_SESSION['user_id'])) {
header("Location: login.php");
exit();
}
?>
<h2>User Dashboard</h2>
<p>
Welcome,
<?php
echo htmlspecialchars($_SESSION['user_name']);
?>
</p>
<p>You are successfully logged in.</p>
Sample Output
When the user is logged in:
User Dashboard
Welcome, Rahul
You are successfully logged in.
When the user is not logged in:
The user is redirected to login.php.
Explanation
session_start()accesses the existing session.isset()checks whether the user ID exists in the session.- If the user ID is missing, PHP redirects the visitor to
login.php. header()sends the redirect response.exit()stops the remaining PHP code from executing.
This is called a protected page because only authenticated users can access it.
Concepts Covered
- Protected dashboard
- Session checking
isset()- Header redirection
- Authentication checks
- Access protection
Question 7: Create a Logout System Using PHP Sessions
Problem Statement
Create a PHP program that logs out the currently authenticated user by clearing their session information and destroying the session.
PHP Solution
<?php
session_start();
// Remove all session variables
$_SESSION = [];
// Destroy the session
session_destroy();
echo "You have been logged out successfully.";
?>
Sample Output
You have been logged out successfully.
Explanation
session_start()accesses the current session.$_SESSION = []removes all session variables.session_destroy()destroys the session data stored on the server.- The user is no longer authenticated through that session.
In a production application using session cookies, also expire the session cookie using the same cookie parameters before destroying the session.
For example, the logout page can redirect the user to the login page after the session has been cleared.
Concepts Covered
- PHP logout system
- Session variables
session_destroy()- Session management
- User logout
Question 8: Implement Role-Based Authorization for Admin and Users
Problem Statement
Create a PHP program that checks the logged-in user’s role. If the user is an administrator, display the admin dashboard. Otherwise, display the regular user dashboard.
Assume the login system has already stored the user’s role in the session.
PHP Solution
<?php
session_start();
if (!isset($_SESSION['user_id'])) {
echo "Please log in first.";
exit();
}
$role = $_SESSION['user_role'] ?? '';
if ($role === "admin") {
echo "Welcome to the Admin Dashboard.";
} elseif ($role === "user") {
echo "Welcome to the User Dashboard.";
} else {
echo "Access denied.";
}
?>
Sample Output
When the role is admin:
Welcome to the Admin Dashboard.
When the role is user:
Welcome to the User Dashboard.
Explanation
Authorization decides what an authenticated user is allowed to access.
$_SESSION['user_role']contains the user’s role.===compares the role with the expected value.- An administrator receives access to the admin dashboard.
- A regular user receives access to the user dashboard.
- An unknown role receives an access-denied message.
Authentication and authorization are different:
| Authentication | Authorization |
|---|---|
| Checks who the user is | Checks what the user can access |
| Verifies login credentials | Checks permissions or roles |
| Happens during login | Happens when accessing protected resources |
Important: Never trust a role supplied by a form or URL. Read the role from a trusted server-side session or verify it against the database.
Concepts Covered
- Role-based authorization
- Admin and user roles
- Session-based access control
- Conditional statements
- Authentication vs authorization
Question 9: Restrict Access to an Admin-Only Page
Problem Statement
Create an admin-only page that allows administrators to access sensitive information. Regular users and visitors who are not logged in must not be allowed to access it.
PHP Solution
<?php
session_start();
if (!isset($_SESSION['user_id'])) {
header("Location: login.php");
exit();
}
if (($_SESSION['user_role'] ?? '') !== "admin") {
http_response_code(403);
echo "Access denied. Admin permission required.";
exit();
}
?>
<h2>Admin Panel</h2>
<p>Welcome to the administration area.</p>
<p>You can manage users and application settings.</p>
Sample Output
When an administrator accesses the page:
Admin Panel
Welcome to the administration area.
You can manage users and application settings.
When a regular user accesses the page:
Access denied. Admin permission required.
The server also returns HTTP status code 403 for the unauthorized request.
Explanation
session_start()loads the user’s session.isset()checks whether the user is logged in.header()redirects unauthenticated visitors to the login page.$_SESSION['user_role']checks the user’s role.http_response_code(403)sends a Forbidden HTTP status.exit()prevents unauthorized users from accessing the remaining page content.
This is an example of authorization because the application checks whether the logged-in user has administrator permission.
Concepts Covered
- Admin-only pages
- Role verification
- HTTP 403 status
- Access control
- Protected resources
- Authorization checks
Question 10: Build a Complete User Authentication System
Problem Statement
Create a simple PHP authentication application with the following features:
- Register a new user.
- Store the password as a secure hash.
- Log in using email and password.
- Store authenticated user information in a session.
- Display a protected dashboard.
- Log out the user.
Create three files:
register.phplogin.phpdashboard.php
You can create a separate logout.php file for logout functionality.
File 1: register.php
<?php
$conn = new mysqli("localhost", "root", "", "auth_db");
if ($conn->connect_error) {
die("Database connection failed.");
}
$message = "";
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$name = trim($_POST['name'] ?? '');
$email = trim($_POST['email'] ?? '');
$password = $_POST['password'] ?? '';
if (
$name === "" ||
!filter_var($email, FILTER_VALIDATE_EMAIL) ||
strlen($password) < 8
) {
$message = "Enter valid details. Password must be at least 8 characters.";
} else {
$hashedPassword = password_hash(
$password,
PASSWORD_DEFAULT
);
$sql = "INSERT INTO users (name, email, password)
VALUES (?, ?, ?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param(
"sss",
$name,
$email,
$hashedPassword
);
if ($stmt->execute()) {
$message = "Registration successful. Please log in.";
} else {
if ($stmt->errno === 1062) {
$message = "This email is already registered.";
} else {
$message = "Unable to complete registration.";
}
}
$stmt->close();
}
}
?>
<h2>User Registration</h2>
<form method="POST">
<input type="text" name="name" placeholder="Enter Name" required>
<br><br>
<input type="email" name="email" placeholder="Enter Email" required>
<br><br>
<input type="password" name="password" placeholder="Enter Password" minlength="8" required>
<br><br>
<button type="submit">Register</button>
</form>
<p><?php echo htmlspecialchars($message); ?></p>
<a href="login.php">Already registered? Login here</a>
File 2: login.php
<?php
session_start();
$conn = new mysqli("localhost", "root", "", "auth_db");
if ($conn->connect_error) {
die("Database connection failed.");
}
$message = "";
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$email = trim($_POST['email'] ?? '');
$password = $_POST['password'] ?? '';
$sql = "SELECT id, name, email, password, role
FROM users
WHERE email = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $email);
$stmt->execute();
$result = $stmt->get_result();
if ($user = $result->fetch_assoc()) {
if (password_verify($password, $user['password'])) {
session_regenerate_id(true);
$_SESSION['user_id'] = $user['id'];
$_SESSION['user_name'] = $user['name'];
$_SESSION['user_role'] = $user['role'];
header("Location: dashboard.php");
exit();
} else {
$message = "Invalid email or password.";
}
} else {
$message = "Invalid email or password.";
}
$stmt->close();
}
?>
<h2>User Login</h2>
<form method="POST">
<input type="email" name="email" placeholder="Enter Email" required>
<br><br>
<input type="password" name="password" placeholder="Enter Password" required>
<br><br>
<button type="submit">Login</button>
</form>
<p><?php echo htmlspecialchars($message); ?></p>
<a href="register.php">Create a new account</a>
File 3: dashboard.php
<?php
session_start();
if (!isset($_SESSION['user_id'])) {
header("Location: login.php");
exit();
}
?>
<h2>User Dashboard</h2>
<p>
Welcome,
<?php echo htmlspecialchars($_SESSION['user_name']); ?>
</p>
<p>
Your Role:
<?php echo htmlspecialchars($_SESSION['user_role']); ?>
</p>
<a href="logout.php">Logout</a>
File 4: logout.php
<?php
session_start();
$_SESSION = [];
if (ini_get("session.use_cookies")) {
$params = session_get_cookie_params();
setcookie(
session_name(),
'',
time() - 42000,
$params['path'],
$params['domain'],
$params['secure'],
$params['httponly']
);
}
session_destroy();
header("Location: login.php");
exit();
?>
Sample Output
Step 1: Registration
User Registration
Enter Name: Rahul
Enter Email: rahul@gmail.com
Enter Password: ********
Registration successful. Please log in.
Step 2: Login
User Login
Enter Email: rahul@gmail.com
Enter Password: ********
Step 3: Dashboard
User Dashboard
Welcome, Rahul
Your Role: user
Logout
Step 4: Logout
After clicking Logout, the session is destroyed and the user is redirected to the login page.
Explanation
This project combines the major concepts covered in this chapter.
1. Registration
The registration page receives user details, validates the basic inputs, hashes the password, and stores the information in the database.
2. Password Hashing
$hashedPassword = password_hash(
$password,
PASSWORD_DEFAULT
);
The original password is never stored in the database.
3. Authentication
The login page searches for the user’s email and verifies the entered password using password_verify().
4. Session Management
After successful authentication, the application creates a session and stores the user’s ID, name, and role.
5. Protected Dashboard
The dashboard checks the session before displaying user information. Visitors without a valid login session are redirected.
6. Logout
The logout page clears session information, expires the session cookie, destroys the session, and redirects the user to the login page.
Important security improvements for a production application:
- Add CSRF protection to registration and login forms.
- Use HTTPS and secure session cookie settings.
- Add login rate limiting to reduce password-guessing attacks.
- Validate all inputs on the server.
- Use a generic login error message.
- Keep database credentials outside publicly accessible files.
- Check user permissions on every protected page and sensitive action.
- Use a trusted configuration for session cookies and regenerate session IDs after authentication.
- Consider
password_needs_rehash()to update password hashes when PHP’s default hashing algorithm or cost changes.
Concepts Covered
- User registration
- Password hashing
- Password verification
- MySQLi prepared statements
- User authentication
- PHP Authentication sessions
- Session ID regeneration
- Protected dashboard
- User logout
- Authentication and authorization
Key Takeaways
- Password hashing protects user passwords stored in a database.
password_hash()generates a secure password hash.password_verify()checks whether an entered password matches a stored hash.- Never store passwords as plain text.
- PHP Authentication verifies the identity of a user.
- PHP Authorization determines what an authenticated user is allowed to access.
- PHP sessions maintain login information across page requests.
session_regenerate_id(true)helps protect against session fixation after login.- Protected pages must check authentication before displaying sensitive information.
- Role-based authorization can provide different permissions to administrators and regular users.
- Logout should clear session data and expire the session cookie.
Frequently Asked Questions (FAQs)
1. What is password hashing in PHP?
Password hashing converts a plain-text password into a one-way hash using a secure algorithm. PHP provides the password_hash() function for this purpose.
2. What is the difference between password_hash() and password_verify()?
password_hash() generates a password hash, while password_verify() checks whether an entered password matches an existing hash.
3. Why should we not store plain-text passwords?
If a database is exposed, attackers could immediately read plain-text passwords. Storing secure password hashes makes it much harder to recover users’ original passwords.
4. What is authentication in PHP?
Authentication is the process of verifying a user’s identity. A common example is checking an email address and password during login.
5. What is authorization in PHP?
Authorization determines what an authenticated user is allowed to access. For example, an administrator may manage users while a regular user can only view their own dashboard.
6. What is the difference between authentication and authorization in PHP?
Authentication answers, “Who are you?” Authorization answers, “What are you allowed to do?”
7. What is the purpose of PHP sessions in a login system?
PHP sessions store information about an authenticated user so that the application can recognize them while they move between different pages.
8. What is session_regenerate_id() used for?
session_regenerate_id() creates a new session ID. It is commonly used after successful login to help prevent session fixation attacks.
9. How can we protect a PHP page from unauthorized users?
Start the session, check whether the user is authenticated, and verify the required permissions before displaying the protected content.
10. What is role-based access control?
Role-based access control assigns permissions according to user roles. For example, an admin can manage users, while a regular user can access only permitted features.
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
