PHP Sessions and Cookies
PHP sessions and cookies let your site remember visitors between requests. HTTP itself is stateless, so without them every page load would be a stranger. Cookies live in the browser; session data lives on the server and the browser only keeps a session ID cookie.
Starting a PHP Session
Call session_start() before any output. Then read and write the $_SESSION array like any other array.
<?php
session_start();
$_SESSION['views'] = ($_SESSION['views'] ?? 0) + 1;
echo "You have viewed this page {$_SESSION['views']} times.";You have viewed this page 3 times.
A Simple Login Flow
After checking the password, store the user ID in the session and regenerate the session ID to prevent session fixation attacks. On logout, clear and destroy the session.
<?php
session_start();
// login.php (after verifying the password)
session_regenerate_id(true);
$_SESSION['user_id'] = 42;
// any protected page
if (!isset($_SESSION['user_id'])) {
header('Location: /login.php');
exit;
}
echo "Welcome back, user #{$_SESSION['user_id']}";
// logout.php
// $_SESSION = [];
// session_destroy();Welcome back, user #42
Setting Cookies With setcookie
Cookies are small values the browser sends back with each request. Like sessions, they must be set before any output. Use the options array for modern security flags.
<?php
setcookie('theme', 'dark', [
'expires' => time() + 60 * 60 * 24 * 30, // 30 days
'path' => '/',
'secure' => true,
'httponly' => true,
'samesite' => 'Lax',
]);
// On the next request:
$theme = $_COOKIE['theme'] ?? 'light';
echo "Theme: $theme";Theme: dark
Session vs Cookie
- Session data is stored on the server; cookies are stored in the browser
- Users can read and edit cookies, so never store secrets or trust them blindly
- Sessions end when the browser closes or after a timeout; cookies can last for months
- Use sessions for login state and carts, cookies for preferences like theme or language
Deleting a Cookie
To delete a cookie, set it again with an expiry time in the past.
<?php
setcookie('theme', '', time() - 3600, '/');
echo "Cookie removed";Cookie removed
Frequently asked questions
What is the difference between a session and a cookie in PHP?
A cookie stores data in the browser. A session stores data on the server and uses a cookie only to hold the session ID, which makes it safer for sensitive state.
Why do I get "headers already sent" errors?
session_start(), setcookie() and header() must run before any output, including whitespace or HTML before <?php. Move them to the top of the script.
How long does a PHP session last?
By default until the browser closes or about 24 minutes of inactivity (session.gc_maxlifetime = 1440 seconds). You can change these settings in php.ini.