Ajax session verification
For a separate project, we implemented a specification that performs asynchronous communication without triggering a browser reload when switching dropdown selections. Since session tokens were being issued, we encountered an issue where session expiration caused the dropdown to become unresponsive during switching.
The session tags are as follows.
HTML
<input type="hidden" name="token" value="<?= htmlspecialchars($_SESSION['token']) ?>">To resolve this, we decided to make the determination at the top level of the system.
PHP
if (isset($_GET['check'])) {
header('Content-Type: application/json');
$active = isset($_SESSION['token']);
echo json_encode(['active' => $active]);
exit;
}And at the very bottom of the HTML, check the session status every 60 seconds.
JavaScript
async function checker() {
const res = await fetch('?check=1', { credentials: 'include' });
const data = await res.json();
return data.active;
}
setInterval(async () => {
const active = await checker();
if (!active) {
location.href = '/login.php';
}
}, 60000);We recommend implementing it in the best way possible.