Tsallaka zuwa abun ciki
Justice Tech School

Sessions and Cookies

HTTP is stateless, so PHP remembers visitors with sessions: call session_start() before any output, then read and write $_SESSION. Cookies are stored in the browser with setcookie(). Never store passwords in either. Browser behaviour cannot run on this page, so the example is shown without output.

Example
<?php
session_start();
if (!isset($_SESSION["visits"])) {
  $_SESSION["visits"] = 0;
}
$_SESSION["visits"]++;
echo "You have visited " . $_SESSION["visits"] . " times";

setcookie("theme", "dark", time() + 3600 * 24 * 30, "/");

Exercise

Start a session.

();

Quiz Test

Where is session data kept?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.