DALT.PHP

Session Management

Learn how to persist data across requests with sessions and flash data

Lesson 6: Session Management

Sessions allow you to store data that persists across multiple HTTP requests.

What are Sessions?

HTTP is stateless - each request is independent. Sessions solve this by:

  1. Creating a unique session ID
  2. Storing it in a cookie on the user's browser
  3. Using it to retrieve stored data on subsequent requests
Request 1: Login → Store user in session
Request 2: View profile → Retrieve user from session
Request 3: Logout → Destroy session

Basic Session Usage

Starting a Session

// In public/index.php
session_name('DALT_SESSION');
session_start();

Storing Data

$_SESSION['user'] = [
    'email' => 'user@example.com',
    'name' => 'John Doe'
];

Retrieving Data

if (isset($_SESSION['user'])) {
    $email = $_SESSION['user']['email'];
}

Removing Data

unset($_SESSION['user']);

The Session Class

DALT.PHP provides a Session helper:

// Store data
Session::put('key', 'value');

// Retrieve data
$value = Session::get('key', 'default');

// Check if exists
if (Session::has('key')) {
    // Key exists
}

// Flash data (one-time)
Session::flash('success', 'Post created!');

// Destroy session
Session::destroy();

Flash Data

Flash data is available only on the next request, then automatically removed.

Setting Flash Data

// After creating a post
Session::flash('success', 'Post created successfully!');
redirect('/posts');

Retrieving Flash Data

// On the next request
$message = Session::get('success');
// Returns: "Post created successfully!"

// On subsequent requests
$message = Session::get('success');
// Returns: null (already removed)

Flash Data Lifecycle

Request 1: Session::flash('key', 'value')
          → Stored in $_SESSION['_flash']['key']
          
Request 2: Session::get('key')
          → Moved to $_SESSION['key']
          → Available for this request
          
Request 3: Session::get('key')
          → Removed from session
          → Returns null

Common Use Cases

Success Messages

// Controller
Session::flash('success', 'Profile updated!');
redirect('/profile');

// View
<?php if ($message = Session::get('success')): ?>
    <div class="alert alert-success">
        <?= $message ?>
    </div>
<?php endif; ?>

Error Messages

// Controller
Session::flash('error', 'Something went wrong!');
redirect('/posts');

// View
<?php if ($error = Session::get('error')): ?>
    <div class="alert alert-error">
        <?= $error ?>
    </div>
<?php endif; ?>

Form Data (Old Input)

// Controller - validation failed
Session::flash('old', $_POST);
Session::flash('errors', $errors);
redirect('/posts/create');

// View - repopulate form
<input 
    type="text" 
    name="title" 
    value="<?= Session::get('old')['title'] ?? '' ?>"
>

Shopping Cart

// Add to cart
$cart = Session::get('cart', []);
$cart[] = $product;
Session::put('cart', $cart);

// View cart
$cart = Session::get('cart', []);

Session Security

Session Regeneration

Regenerate session ID after login to prevent session fixation:

public function login($user) {
    $_SESSION['user'] = $user;
    session_regenerate_id(true); // Important!
}

Session Timeout

Set session lifetime in php.ini or at runtime:

// 30 minutes
ini_set('session.gc_maxlifetime', 1800);
session_set_cookie_params(1800);

Secure Cookies

session_set_cookie_params([
    'lifetime' => 0,
    'path' => '/',
    'domain' => '',
    'secure' => true,   // HTTPS only
    'httponly' => true, // No JavaScript access
    'samesite' => 'Lax' // CSRF protection
]);

The Session Class Implementation

class Session {
    public static function put($key, $value) {
        $_SESSION[$key] = $value;
    }
    
    public static function get($key, $default = null) {
        return $_SESSION[$key] ?? $_SESSION['_flash'][$key] ?? $default;
    }
    
    public static function flash($key, $value) {
        $_SESSION['_flash'][$key] = $value;
    }
    
    public static function unflash() {
        unset($_SESSION['_flash']);
    }
    
    public static function has($key) {
        return isset($_SESSION[$key]);
    }
    
    public static function destroy() {
        $_SESSION = [];
        session_destroy();
        
        $params = session_get_cookie_params();
        setcookie('DALT_SESSION', '', time() - 3600, $params['path']);
    }
}

Debugging Sessions

View Session Data

dd($_SESSION);

Check Flash Data

dd([
    'session' => $_SESSION,
    'flash' => $_SESSION['_flash'] ?? 'none'
]);

Test Flash Lifecycle

// Request 1
Session::flash('test', 'value');
dd($_SESSION); // See _flash array

// Request 2
$value = Session::get('test');
dd(['value' => $value, 'session' => $_SESSION]);

// Request 3
$value = Session::get('test');
dd(['value' => $value, 'session' => $_SESSION]); // Should be null

Common Issues

Flash Data Not Persisting

Cause: unflash() not called at end of request

Fix: Ensure Session::unflash() is called in index.php

Flash Data Disappears Immediately

Cause: Wrong order in get() method

Fix: Check $_SESSION[$key] before $_SESSION['_flash'][$key]

Session Not Starting

Cause: session_start() not called or called after output

Fix: Call session_start() at the top of index.php

Tip: Sessions must be started before any output is sent to the browser!

Ready for the Challenge?

On this page