Editor's note (2026): The code examples in the original 2014 version were missing from the page. We've added complete examples and session security tips.
Sessions let you store information for each visitor and use it across multiple pages, for example to keep someone logged in. In PHP, session data is stored in $_SESSION['varname'].
Sessions vs. cookies
- Cookies are stored in the visitor's browser, so users can see and change them. Never put sensitive information such as passwords or payment details in cookies.
- Session data is stored on the server. The browser only keeps a session ID (in a cookie) that links the visitor to their data.
Starting a session
Call session_start() at the top of every page that uses sessions, before any output:
<?php
session_start();
This starts a new session or resumes the visitor's existing one.
Example: setting session variables
first.php
<?php
session_start();
$_SESSION['author'] = 'Jane Smith';
$_SESSION['website'] = 'example.com';
echo 'Session variables are set.';
Example: reading session variables
second.php
<?php
session_start();
if (isset($_SESSION['author'], $_SESSION['website'])) {
echo 'Author: ' . htmlspecialchars($_SESSION['author']) . '<br>';
echo 'Website: ' . htmlspecialchars($_SESSION['website']);
} else {
echo 'No session data yet. Visit first.php first.';
}
Visit first.php first so the variables exist, then open second.php.
Ending a session
On a logout page, clear and destroy the session:
<?php
session_start();
$_SESSION = [];
session_destroy();
Security tips
- Call
session_regenerate_id(true)after a user logs in to prevent session fixation. - Use HTTPS, and set session cookies as
Secure,HttpOnly, andSameSite. - Don't store passwords in the session; store a user ID instead.
- Set a sensible session timeout.
Need help building secure logins for your web application? I.T. For Less can help — contact us.