Configure and start the session
<?php
session_set_cookie_params([
'lifetime' => 0,
'path' => '/',
'secure' => true, // Use HTTPS.
'httponly' => true,
'samesite' => 'Lax',
]);
session_start();
After successful credential verification
session_regenerate_id(true);
$_SESSION['user_id'] = (int) $user['id'];
Protect a page
<?php
if (empty($_SESSION['user_id'])) {
header('Location: /login.php');
exit;
}
Security notes
Set session cookie options before session_start(). Use HTTPS throughout the site, expire sessions appropriately, implement logout by clearing session data and destroying the session, and apply authorization checks to individual resources.