agyanadda@gmail.com

PHP Sessions

PHP Forms and Web 1 min read Updated Dec 1, 2026 Topic 25 of 36

HTTP forgets the visitor after every page. A session remembers data (like who is logged in) across pages.

How it works

  1. session_start() creates or resumes a session
  2. PHP sends a cookie PHPSESSID with a random ID
  3. 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.

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which function must be called before using $_SESSION?

Exercise 2 True / False

Session data is stored on the server.

Exercise 3 Fill in the Blank

session(true) creates a new session ID after login.

Frequently Asked Questions

Sessions. The data stays on the server; the browser only holds a random ID. Cookies store data in the browser, where users can read and change it.