Sessions and Cookies
HTTP has no memory. Every request is a fresh conversation, and a page cannot remember that you logged in a minute ago unless something carries the memory. Sessions and cookies are that something.
A cookie is a small piece of data the server asks the browser to keep. On the next request the browser sends it back. Cookies work for things like preferences and visit counts. In PHP you set one with setcookie(), and it arrives on later pages inside $_COOKIE.
A session goes further. PHP assigns the visitor an id, stores the id in a cookie, and keeps the session data on the server. Your code only touches $_SESSION, and PHP handles the rest. This is how logins work: after the visitor authenticates, you store their user id in the session and every page knows who they are.
The one rule that causes the most trouble: sessions and cookies must be started before any output. A single echo, a stray space, or an invisible UTF-8 byte before session_start() triggers the "headers already sent" error, because the response header that sets the cookie must arrive before the body.
Working with sessions
session_start() opens the session on every page that needs it. You read and write $_SESSION like any array. session_destroy() clears everything, usually at logout, and unset($_SESSION["key"]) removes one value.
session_start();
$_SESSION["user_id"] = 42;
// on another page
session_start();
if (isset($_SESSION["user_id"])) {
echo "Welcome back, user " . $_SESSION["user_id"];
}
Setting a cookie
setcookie(name, value, expires) sends a cookie with the response. The third argument is a Unix timestamp for when it expires. Read it back on the next request from $_COOKIE.
$expires = time() + 60 * 60 * 24 * 30; // 30 days
setcookie("theme", "dark", $expires);
// next request
$theme = $_COOKIE["theme"] ?? "light";
Syntax
<?php
session_start();
if (!isset($_SESSION["visits"])) {
$_SESSION["visits"] = 0;
}
$_SESSION["visits"]++;
echo "You have visited " . $_SESSION["visits"] . " times.";
?>
session_start() Must Be First
session_start() must be before any output — even a space before <?php breaks it with headers already sent.
<?php session_start(); ?> // first line, no space before
Good to know
- Sessions store data on the server, keyed by a cookie id.
- session_start() must run before any output.
- Cookies are set with setcookie() and read from $_COOKIE.
- session_destroy() logs a visitor out completely.