Web Development Lesson 15 of 17
PHP Sessions and Cookies — Logins and Remembering Users
Remember data between pages with sessions, build a login and logout, protect pages, hash passwords with password_hash, and use cookies for simple preferences.
Each page request is separate: by default, PHP forgets everything once a page finishes. To remember a logged-in user or a shopping cart across pages, use sessions. For small preferences stored in the browser, use cookies.
Sessions
<?php
session_start(); // must be called before any output
$_SESSION["views"] = ($_SESSION["views"] ?? 0) + 1;
echo "You've opened this page " . $_SESSION["views"] . " time(s).";
Refresh the page and the number goes up. PHP stores $_SESSION data on the server and gives the browser a session ID cookie to recognize it on the next request.
Storing passwords: password_hash
Never store passwords as plain text. If your database leaks, every password would be exposed. Store a hash instead:
<?php
$hash = password_hash("Mabuhay2026!", PASSWORD_DEFAULT);
echo strlen($hash) > 50 ? "Hash created\n" : "?";
var_dump(password_verify("Mabuhay2026!", $hash));
var_dump(password_verify("wrongpass", $hash));
Output
Hash created bool(true) bool(false)
password_hash creates a different hash each time (it adds a random "salt"), and password_verify checks a typed password against it. Don't use md5 or sha1 for passwords; they're far too fast to crack.
A simple login
login.php:
<?php
session_start();
// In a real app, these come from the database (see the PDO lesson).
$users = ["teacher" => password_hash("guro123", PASSWORD_DEFAULT)];
$error = "";
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$user = trim($_POST["username"] ?? "");
$pass = $_POST["password"] ?? "";
if (isset($users[$user]) && password_verify($pass, $users[$user])) {
session_regenerate_id(true); // protect against session fixation
$_SESSION["user"] = $user;
header("Location: dashboard.php");
exit;
}
$error = "Wrong username or password.";
}
?>
<form method="post">
<input name="username" placeholder="Username">
<input name="password" type="password" placeholder="Password">
<button>Log in</button>
<p><?= htmlspecialchars($error) ?></p>
</form>
dashboard.php (a protected page):
<?php
session_start();
if (!isset($_SESSION["user"])) {
header("Location: login.php");
exit;
}
?>
<h1>Welcome, <?= htmlspecialchars($_SESSION["user"]) ?>!</h1>
<a href="logout.php">Log out</a>
logout.php:
<?php
session_start();
$_SESSION = [];
session_destroy();
header("Location: login.php");
exit;
A shopping cart in the session
<?php
session_start();
$_SESSION["cart"] ??= [];
if (isset($_POST["add"])) {
$item = $_POST["add"];
$_SESSION["cart"][$item] = ($_SESSION["cart"][$item] ?? 0) + 1;
}
foreach ($_SESSION["cart"] as $item => $qty) {
echo htmlspecialchars($item) . " x $qty<br>";
}
??= assigns a value only if the variable is null or not set.
Cookies
A cookie is a small piece of data stored in the visitor's browser and sent back with every request:
<?php
if (isset($_GET["theme"])) {
$theme = $_GET["theme"] === "dark" ? "dark" : "light";
setcookie("theme", $theme, [
"expires" => time() + 60 * 60 * 24 * 30, // 30 days
"path" => "/",
"httponly" => true,
"samesite" => "Lax",
]);
} else {
$theme = $_COOKIE["theme"] ?? "light";
}
echo "Current theme: $theme";
| Session | Cookie | |
|---|---|---|
| Stored on | Server | Visitor's browser |
| User can see/edit it? | No | Yes |
| Lasts | Until the browser closes or logout (by default) | Until it expires |
| Use for | Logins, carts, anything private | Preferences like theme or language |
Never store passwords or "is admin" flags in cookies; users can change them.
Quick Quiz
Check what you learned. Walang grade ito, practice lang. 🙂
By Sir Reyel · Last updated 2026-12-04