Why sessions?
HTTP forgets you after each request. Sessions let the server remember a visitor across pages, for example to keep them logged in.
Using sessions
<?php
session_start(); // must be called before any output
$_SESSION["user"] = "Asha"; // store data
// on another page
session_start();
echo "Hello, " . ($_SESSION["user"] ?? "Guest");PHP stores the data on the server and gives the browser a small session ID cookie.
A simple login flow
<?php
session_start();
if ($_SERVER["REQUEST_METHOD"] === "POST") {
// In a real app, look up the user in the database
$hash = password_hash("secret123", PASSWORD_DEFAULT); // do this at registration
if ($_POST["email"] === "asha@example.com" && password_verify($_POST["password"], $hash)) {
session_regenerate_id(true); // prevents session fixation
$_SESSION["user"] = "Asha";
header("Location: dashboard.php");
exit;
}
$error = "Incorrect email or password.";
}Never store passwords in plain text. Use password_hash() and password_verify().
Protecting a page
<?php
session_start();
if (!isset($_SESSION["user"])) {
header("Location: login.php");
exit;
}Logging out
<?php
session_start();
$_SESSION = [];
session_destroy();
header("Location: login.php");Cookies
setcookie("theme", "dark", [
"expires" => time() + 86400 * 30,
"path" => "/",
"httponly" => true,
"samesite" => "Lax",
]);
echo $_COOKIE["theme"] ?? "light";Use cookies for small preferences. Do not store sensitive information in them.
Practice
Create login, dashboard and logout pages. Redirect visitors who are not logged in.