0, 'path' => '/', 'domain' => '', 'secure' => true, 'httponly' => true, 'samesite' => 'Lax', ]); if (session_status() !== PHP_SESSION_ACTIVE) { session_start(); } } /** * Require a valid login. * IMPORTANT: releases the session lock immediately to avoid deadlocks/timeouts. */ function require_auth(bool $json = true): void { auth_session_start(); $ok = (isset($_SESSION['authed']) && $_SESSION['authed'] === true); // Release the session file lock ASAP. // This prevents other requests from blocking on session_start(). session_write_close(); if (!$ok) { http_response_code(401); if ($json) { header('Content-Type: application/json; charset=utf-8'); echo json_encode(['error' => 'Unauthorized']); } else { header('Content-Type: text/plain; charset=utf-8'); echo "Unauthorized"; } exit; } }