PHP

Lesson 06

Session handling and cookies

Configure session cookies deliberately and regenerate session IDs when authentication state changes.

Good Code

src/Auth/Session.php
<?php declare(strict_types=1);

session_set_cookie_params([
    'lifetime' => 0,
    'path' => '/',
    'secure' => true,
    'httponly' => true,
    'samesite' => 'Lax',
]);

session_start();

function signIn(int $userId): void
{
    session_regenerate_id(true);
    $_SESSION['user_id'] = $userId;
}

Bad Code

login.php
<?php

session_start();

if ($_POST['password'] === $user['password']) {
    $_SESSION['user_id'] = $user['id'];
    $_SESSION['role'] = $_GET['role'];
}

Review Notes

What to review

Good Code

The good version sets cookie flags before starting the session and regenerates the session ID when the user signs in.

Bad Code

The bad version uses default cookie behavior, does not rotate the session ID, and trusts a request parameter for authorization state.

Takeaways

  • Session code should make cookie flags and identity transitions visible to reviewers.