PHPPHP
IntermediateLesson 12 of 16

Sessions, Cookies & Login – PHP

Storing state between requests and building a secure login.

HTTP has no memory. A session stores data on the server and gives the browser only a random ID via a cookie. Call session_start() before you send any output, then $_SESSION is available.

<?php
session_start();
$_SESSION["besuche"] = ($_SESSION["besuche"] ?? 0) + 1;
echo "Visit no. ", $_SESSION["besuche"];

A login checks the password with password_verify against the stored hash. Important: after a successful login, renew the session ID (session_regenerate_id(true)), otherwise session fixation is possible.

<?php
declare(strict_types=1);
session_start();

// finde_nutzer() is your own function that fetches a row from the "nutzer" table via PDO
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $nutzer = finde_nutzer($_POST["email"] ?? "");
    if ($nutzer && password_verify($_POST["passwort"] ?? "", $nutzer["passwort_hash"])) {
        session_regenerate_id(true);
        $_SESSION["user_id"] = $nutzer["id"];
        header("Location: /konto.php");
        exit;
    }
    $fehler = "Email or password incorrect.";   // deliberately do not reveal which one was wrong
}

Protected pages check the session; logout empties and destroys it:

<?php
// konto.php
session_start();
if (!isset($_SESSION["user_id"])) {
    header("Location: /login.php");
    exit;
}

// logout.php
session_start();
$_SESSION = [];
session_destroy();
header("Location: /login.php");
exit;

You set your own cookies with setcookie – preferably with the options as an array:

<?php
setcookie("theme", "dark", [
    "expires" => time() + 60 * 60 * 24 * 30,
    "path" => "/",
    "secure" => true,       // HTTPS only
    "httponly" => true,     // not readable by JavaScript
    "samesite" => "Lax",    // protection against cross-site requests
]);
echo $_COOKIE["theme"] ?? "light";   // only visible from the NEXT request on
WarningNever store passwords or permissions in plain text in cookies – cookies belong to the user. When a login fails, do not give the user any hint whether the email or the password was wrong.