Sessions and cookies
The server handles every request to a site separately and remembers nothing about earlier ones. For a visitor to stay "logged in" while moving between pages, you need sessions and cookies.
The examples in this lesson need a web server, so they cannot be run here.
How a session works
On the first visit PHP creates a storage area on the server and gives the browser a random identifier. The browser sends it back with every following request, and PHP uses it to find the right storage. The data itself stays on the server — the visitor only has the identifier.
Starting a session
session_start() opens the session. After it the $_SESSION array is available:
<?php
session_start();
$_SESSION['name'] = 'Anna';The value is saved and is available on any other page of the site that also calls session_start():
<?php
session_start();
echo $_SESSION['name'] ?? 'Guest';A visit counter
Session data can be changed like a regular array:
<?php
session_start();
$_SESSION['visits'] = ($_SESSION['visits'] ?? 0) + 1;
echo "You have opened this page {$_SESSION['visits']} times";Logging in and out
Authentication is built on sessions: after the password is verified, the user's id is stored in the session, and protected pages check that it is there.
<?php
session_start();
if (!isset($_SESSION['user_id'])) {
header('Location: /login.php');
exit;
}On logout the session is destroyed:
<?php
session_start();
session_destroy();Cookies
A cookie is a small value stored in the browser itself. setcookie() creates it, and you read it from the $_COOKIE array on the next request:
<?php
setcookie('theme', 'dark', time() + 60 * 60 * 24 * 30);
$theme = $_COOKIE['theme'] ?? 'light';The third argument is the time until which the cookie is valid: here it is 30 days from now.
What to store where
| Session | Cookie | |
|---|---|---|
| Where the data lives | On the server | In the browser |
| Can the visitor change it | No | Yes |
| Used for | Login, shopping cart | Theme, language |
A common mistake
session_start(), setcookie() and header() must be called before any output to the page — even before a space in front of <?php. Otherwise PHP raises a headers already sent warning and nothing works.
And do not keep anything secret in cookies: the visitor can see their content and change it.