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

PHP Authentication Basics

Authentication is proving you are who you say you are, like showing a library card. PHP compares the password someone types with a safely scrambled copy it saved before.
Syntax
php
$hash = password_hash($password, PASSWORD_DEFAULT);   // store this

if (password_verify($password, $hash)) {
    $_SESSION["user_id"] = $user_id;   // logged in
}

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
// Declare `$storedUsername`, set to "alice"
$storedUsername = "alice";
// Declare `$submittedUsername`, set to "alice"
$submittedUsername = "alice";
// Check whether `$submittedUsername === $storedUsername`
if ($submittedUsername === $storedUsername) {
    // Print "Identity confirmed" to the output
    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
// Declare `$hash`, set to `password_hash("mypassword123", PASSWORD_DEFAULT)`
$hash = password_hash("mypassword123", PASSWORD_DEFAULT);
// Print `$hash . "\n"` to the output
echo $hash . "\n";
// Print a detailed dump (with types) of `password_verify("mypassword123", $hash)`
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
// Call `session_start()`
session_start();
// Set `$_SESSION['user_id']` to `42`
$_SESSION['user_id'] = 42;
// Print `"Logged in as user #" . $_SESSION['user_id']` to the output
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
// Call `session_start()`
session_start();
// Check whether `!isset($_SESSION['user_id'])`
if (!isset($_SESSION['user_id'])) {
    // Print "Redirecting to login page" to the output
    echo "Redirecting to login page";
// Otherwise, run this branch
} else {
    // Print `"Welcome back, user #" . $_SESSION['user_id']` to the output
    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
// Call `session_start()`
session_start();
// Set `$_SESSION['user_id']` to `42`
$_SESSION['user_id'] = 42;
// Call `session_regenerate_id(true)`
session_regenerate_id(true);
// Print "Session ID regenerated to prevent session fixation" to the output
echo "Session ID regenerated to prevent session fixation";
?>
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Storing passwords in plain text, instead of using password_hash.
  2. Comparing passwords with == instead of password_verify.
  3. Forgetting to check the session on protected pages.
Chapter Summary
  • Sessions store data about a user across requests, and cookies store data in the browser.
  • Session and cookie management explain how to create, read, and remove them.
  • Authentication basics build on sessions and cookies to identify users.
🔒

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.