HTTP forgets the visitor after every page. A session remembers data (like who is logged in) across pages.
How it works
session_start()creates or resumes a session- PHP sends a cookie
PHPSESSIDwith a random ID - Data is stored on the server, linked to that ID
Use it
session_start(); // top of every page, before output
$_SESSION['user_id'] = 7; // save
$name = $_SESSION['name'] ?? 'Guest'; // read
unset($_SESSION['cart']); // remove one item
Logout
session_start();
$_SESSION = [];
session_destroy();
Security tips
- Call
session_regenerate_id(true)right after login - Store only an ID, not the password
- Use HTTPS so the session cookie cannot be stolen
Flash messages
Save a message, show it once, then remove it — this is how "Profile updated" alerts work.
Example
Example — Simple login with sessions
PHP
<?php
session_start();
// Demo user (in real apps, read from the database and use password_verify)
$demoEmail = 'student@example.com';
$demoHash = password_hash('secret123', PASSWORD_DEFAULT);
if (isset($_GET['logout'])) {
$_SESSION = [];
session_destroy();
header('Location: ' . strtok($_SERVER['REQUEST_URI'], '?'));
exit;
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if ($_POST['email'] === $demoEmail && password_verify($_POST['password'], $demoHash)) {
session_regenerate_id(true);
$_SESSION['user'] = 'Asha';
$_SESSION['flash'] = 'Login successful!';
} else {
$_SESSION['flash'] = 'Wrong email or password.';
}
}
if (!empty($_SESSION['flash'])) {
echo '<p><strong>' . $_SESSION['flash'] . '</strong></p>';
unset($_SESSION['flash']);
}
if (isset($_SESSION['user'])): ?>
<h3>Welcome, <?= htmlspecialchars($_SESSION['user']) ?>!</h3>
<a href="?logout=1">Logout</a>
<?php else: ?>
<form method="post">
<input name="email" placeholder="student@example.com">
<input name="password" type="password" placeholder="secret123">
<button>Login</button>
</form>
<?php endif; ?>
Log in with student@example.com / secret123. Reload the page — you stay logged in because the session remembers you. Click Logout to end the session.