CodeBlanks Logo Icon CodeBlanks

Storing data with $_SESSION

PHP course · Intermediate · Lesson 83/115

Learn to write data to the $_SESSION superglobal and carry it across pages.

The $_SESSION superglobal

$_SESSION is a superglobal array: it is accessible globally, even inside functions. After session_start() you write data as $_SESSION['key'] = value.

The data is saved to a session file on the server. On later requests with the same session id, PHP loads this file and $_SESSION is ready.

This lets you carry a username, cart contents or theme choice across pages.

Data persists across pages

The power of sessions is persistence. If you write $_SESSION['cart'] = 3 on page_a.php, you read the same value on page_b.php after calling session_start().

The reason: both pages share the same session id. The browser cookie sends the id on every request; PHP loads the right file.

The data survives until you close the session with session_destroy() or the cookie expires.

Exercise Write a user and role to $_SESSION

Call session_start(). Set $_SESSION['user'] to 'Alex' and $_SESSION['role'] to 'admin'. Then print both on separate lines with echo.

Show example solution
Call session_start, assign two keys, then echo $_SESSION['user'] and echo $_SESSION['role'].
Example solution:
<?php
// Write a username and role to $_SESSION, then print them
session_start();
$_SESSION['user'] = 'Alex';
$_SESSION['role'] = 'admin';
echo $_SESSION['user'] . "\n";
echo $_SESSION['role'] . "\n";

Test yourself

  1. Which superglobal stores session data?

    • $_SESSION
    • $_POST
    • $_GET
    • $_COOKIE
    Show answer

    $_SESSION — Correct. The $_SESSION superglobal carries session data across pages.

  2. Write a username to the session

    <?php
    session_start();
    ____
    $_SESSION['cart'] = ['item' => 'book'];
    echo $_SESSION['user'];
    
    Show answer
    <?php
    session_start();
    $_SESSION['user'] = 'Alex';
    $_SESSION['cart'] = ['item' => 'book'];
    echo $_SESSION['user'];
    
  3. Match the write and read flow

    $_SESSION['x'] = 5
    Data is written on page A
    session_start()
    Called first on page B
    echo $_SESSION['x']
    Prints 5 on page B
    session_id()
    Returns the session id

All lessons in Intermediate