Send a CSRF token with fetch()
Put the token in a meta tag and send it as a header on every POST. The server must compare it with the one stored in the session.
AJAX · Send a CSRF token with fetch()Intermediate
// HTML: <meta name="csrf" content="<?= htmlspecialchars($_SESSION['csrf']) ?>">
const token = document.querySelector('meta[name="csrf"]').content;
async function postJson(url, data) {
const res = await fetch(url, {
method: 'POST',
credentials: 'same-origin',
headers: { 'Content-Type': 'application/json', 'X-CSRF-Token': token },
body: JSON.stringify(data)
});
if (!res.ok) throw new Error('HTTP ' + res.status);
return res.json();
}
// PHP side: hash_equals($_SESSION['csrf'], $_SERVER['HTTP_X_CSRF_TOKEN'] ?? '')csrffetchsecurity