Good Code
The good version sets cookie flags before starting the session and regenerates the session ID when the user signs in.
Lesson 06
Configure session cookies deliberately and regenerate session IDs when authentication state changes.
<?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;
}<?php
session_start();
if ($_POST['password'] === $user['password']) {
$_SESSION['user_id'] = $user['id'];
$_SESSION['role'] = $_GET['role'];
}The good version sets cookie flags before starting the session and regenerates the session ID when the user signs in.
The bad version uses default cookie behavior, does not rotate the session ID, and trusts a request parameter for authorization state.