PHP Authentication Basics
In this page:
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
$storedUsername = "alice";
$submittedUsername = "alice";
if ($submittedUsername === $storedUsername) {
echo "Identity confirmed";
}
?>
Login to try C/C++/Java/PHP code in the editor
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
$hash = password_hash("mypassword123", PASSWORD_DEFAULT);
echo $hash . "\n";
var_dump(password_verify("mypassword123", $hash));
?>
Login to try C/C++/Java/PHP code in the editor
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
session_start();
$_SESSION['user_id'] = 42;
echo "Logged in as user #" . $_SESSION['user_id'];
?>
Login to try C/C++/Java/PHP code in the editor
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
session_start();
if (!isset($_SESSION['user_id'])) {
echo "Redirecting to login page";
} else {
echo "Welcome back, user #" . $_SESSION['user_id'];
}
?>
Login to try C/C++/Java/PHP code in the editor
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
session_start();
$_SESSION['user_id'] = 42;
session_regenerate_id(true);
echo "Session ID regenerated to prevent session fixation";
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 5 topics to unlock
0/5 topics done
Complete these topics first: