← Back to PHP Course | Chapter 12: Sessions & Cookies | Lesson 5 of 5

PHP Authentication Basics

What is Authentication?

Authentication is the process of confirming a user really is who they claim to be, typically by comparing a submitted username and password against securely stored records rather than trusting the claim outright.

Example: What is Authentication?

php
<?php
$storedUsername = "alice";
$submittedUsername = "alice";
if ($submittedUsername === $storedUsername) {
    echo "Identity confirmed";
}
?>

Password Hashing

Storing plain-text passwords is a serious security risk if your database is ever breached; password_hash() converts a password into a one-way hash that password_verify() can later check without ever storing the original.

Example: Password Hashing

php
<?php
$hash = password_hash("mypassword123", PASSWORD_DEFAULT);
echo $hash . "\n";
var_dump(password_verify("mypassword123", $hash));
?>

Basic Session-Based Login

A common pattern after a successful login is to save the user's ID in $_SESSION, so subsequent page loads can check that value instead of asking the visitor to log in again on every request.

Example: Basic Session-Based Login

php
<?php
session_start();
$_SESSION['user_id'] = 42;
echo "Logged in as user #" . $_SESSION['user_id'];
?>

Guarding Pages

To protect a private page, check for the expected session variable at the top of the script and redirect to the login page if it's missing, before any sensitive content is rendered.

Example: Guarding Pages

php
<?php
session_start();
if (!isset($_SESSION['user_id'])) {
    echo "Redirecting to login page";
} else {
    echo "Welcome back, user #" . $_SESSION['user_id'];
}
?>

Authentication Best Practices

Regenerating the session ID immediately after a successful login is a key defense against session fixation attacks, where an attacker tricks a victim into using a session ID the attacker already controls.

Example: Authentication Best Practices

php
<?php
session_start();
$_SESSION['user_id'] = 42;
session_regenerate_id(true);
echo "Session ID regenerated to prevent session fixation";
?>
🔒

Chapter Quiz — Complete all 5 topics to unlock

0/5 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.