By default, each web request is completely independent — a server has no memory of who visited a moment ago. Sessions and cookies are the two tools PHP gives you to bridge that gap, and they solve it differently.
Without either one, a website couldn't keep you logged in between pages, remember what's in your shopping cart, or recall a language preference. Every request would start from a completely blank slate.
A cookie is a small piece of data PHP asks the visitor's browser to store, which the browser then sends back automatically on every future request to that site:
<?php
// Set a cookie that lasts 30 days
setcookie("username", "Priya", time() + (30 * 24 * 60 * 60));
// On a later request:
echo $_COOKIE["username"] ?? "No cookie set";
?>Cookies must be set before any output
setcookie() must be called before any HTML or other output — even a single blank line before <?php in the file is enough to cause a "headers already sent" error, since cookies are sent as HTTP headers.
A session keeps data on the server instead, and only sends the visitor a small ID pointing at it — meaning the actual data never passes through the visitor's browser at all, which matters for anything sensitive.
<?php
session_start(); // must be the very first thing in the script
$_SESSION["username"] = "Priya";
// On a later request, after session_start() again:
echo $_SESSION["username"] ?? "Not logged in";
?>session_start() has the same "before any output" requirement as setcookie(), and needs to run on every page that wants access to the session, not just the one that created it.
| Where data lives | Good for | |
|---|---|---|
| Cookie | The visitor's browser | Non-sensitive preferences (theme, language) that should survive even after closing the browser |
| Session | The server | Login state, cart contents — anything sensitive or that shouldn't be tamperable from the browser |
<?php
session_start();
session_destroy(); // used for a "log out" action
?>