Sessions & Cookies in PHP
Sessions & Cookies in PHP
HTTP is stateless, meaning the server forgets you between page requests. Sessions and cookies are how PHP remembers a user, for example to keep them logged in. A session stores data on the server; a cookie stores a small piece of data in the browser. Together they make features like login and shopping carts possible.
What is a session?
A session keeps data on the server and gives the browser a small ID cookie to identify it on each request. Session data is more secure than cookies because the actual values never leave the server.
<?php
// Always call this before any output, at the top of the page.
session_start();
// Store a value in the session.
$_SESSION["username"] = "Sanya";
echo "Session set.";
?>
On another page, read the value back:
<?php
session_start();
// Read with a default in case it is not set.
$user = $_SESSION["username"] ?? "Guest";
echo "Welcome, " . htmlspecialchars($user);
?>
session_start() must run before any HTML is sent, because it sets a header.
Ending a session (logout)
To log a user out, clear the session data and destroy the session.
<?php
session_start();
$_SESSION = []; // empty the session array
session_destroy(); // destroy the session on the server
echo "You have been logged out.";
?>
What is a cookie?
A cookie is a small piece of data stored in the user's browser and sent back with each request. Use cookies for non-sensitive preferences, such as a chosen theme or language.
<?php
// Set a cookie that lasts 7 days.
// setcookie must be called before any output.
setcookie(
"theme",
"dark",
time() + (7 * 24 * 60 * 60) // expiry: now + 7 days in seconds
);
echo "Cookie will be available on the next request.";
?>
Read a cookie on a later request through the $_COOKIE array:
<?php
// A cookie set on a previous request is now readable.
$theme = $_COOKIE["theme"] ?? "light";
echo "Current theme: " . htmlspecialchars($theme);
?>
A cookie you set is not available in $_COOKIE until the next request.
Want to learn this properly?
Join the waitlist for our courses — beginner-friendly, project-first classes in Jalgaon.
Browse coursesDeleting a cookie
Set its expiry to a time in the past.
<?php
setcookie("theme", "", time() - 3600); // expired one hour ago
?>
Sessions vs cookies
| Feature | Session | Cookie |
|---|---|---|
| Where stored | On the server | In the browser |
| Good for | Login state, sensitive data | Preferences, small flags |
| Visible to user | No (only the ID) | Yes |
| Default lifetime | Until browser closes | Whatever you set |
A simple login check
<?php
session_start();
// Pretend the user just logged in successfully.
$_SESSION["logged_in"] = true;
// On protected pages, guard access:
if (empty($_SESSION["logged_in"])) {
echo "Please log in first.";
} else {
echo "Welcome to your dashboard.";
}
?>
For real applications, set secure cookie flags (Secure, HttpOnly, SameSite) and regenerate the session ID after login with session_regenerate_id(true) to reduce hijacking risk.
Common mistakes
- Calling
session_start()after output, which triggers a "headers already sent" warning. Put it at the very top. - Storing sensitive data in cookies. Cookies live in the browser and can be read or edited by the user.
- Forgetting that a freshly set cookie is not in
$_COOKIEuntil the next request. - Not validating session data, treating it as automatically trustworthy without checks.
FAQ
When should I use a session vs a cookie? Use sessions for anything sensitive or important, like login state. Use cookies for small, non-sensitive preferences.
Why do I get "headers already sent"?
You produced output (even a blank line or space) before calling session_start() or setcookie(). Move those calls above any output.
How do I keep a user logged in across visits? Use sessions for the active login, and consider a secure long-lived cookie token for "remember me", validated on the server.
Keep learning
Back to the PHP & MySQL hub, revisit Handling Forms in PHP, or continue to PHP + MySQL CRUD.
Build login systems with mentor support. Join the waitlist for the PHP course at Infoplanet in Jalgaon.
Want to learn this properly?
Join the waitlist for our courses — beginner-friendly, project-first classes in Jalgaon.
Browse coursesFounder, Infoplanet
Atul Kabra founded Infoplanet in 2001 and has spent over two decades teaching programming — C, C++, Java, databases and more — to students across Maharashtra.
Related guides
Arrays in PHP: Indexed, Associative & Multidimensional
Understand PHP arrays - indexed, associative, and multidimensional - and the most useful array functions, with examples for adding, reading, and looping over data.
Control Flow in PHP: if, switch & Loops
Make PHP code decide and repeat with control flow: if/else, switch, the match expression, and the for, while, and foreach loops, with clear examples.
Handling Forms in PHP (GET & POST)
Handle HTML forms in PHP: the difference between GET and POST, reading input from the superglobals, validating data, and escaping output to prevent XSS.
