Forms, htmx and JSON
Forms
pages/signup.php<?php
params();
allow('GET', 'POST');
$form = ['email' => ''];
$errors = [];
if (is_post()) {
csrf_check(); // bad token → 403
rate_limit('signup:' . ip_key(), 5, 60); // 5 a minute, else 429
[$form, $errors] = validate(input(), ['email' => 'required|email|max:254']);
if (!$errors) {
q('INSERT INTO signups (email) VALUES (?)', [$form['email']]);
flash('ok', 'Signed up');
redirect('/signup', 303); // 303 after success: a reload never posts twice
}
http_response_code(422); // failure: show the form, errors and input again
}
layout('site', ['title' => 'Sign up']);
?>
<form method="post">
<?= csrf_field() ?>
<input name="email" value="<?= e($form['email']) ?>">
<?php if (isset($errors['email'])): ?><p class="error"><?= e($errors['email']) ?></p><?php endif ?>
<button>Sign up</button>
</form>
htmx
One URL answers both the full page and a fragment: check is_htmx(), print the fragment and exit, and send Vary: HX-Request. Writes use hx-post on a form that contains csrf_field(); a button outside a form gets hx-headers with X-CSRF-Token on a parent element.
JSON APIs
pages/api/notes.php<?php
[$raw] = params(0, 1);
allow('GET', 'POST');
$id = as_id($raw);
if ($id !== null) allow('GET');
if ($id !== null) {
json(['note' => one('SELECT id, text FROM notes WHERE id = ?', [$id]) ?? abort(404)]);
}
if (is_post()) {
require_login(); // under /api: 401 JSON when not logged in
csrf_check(); // X-CSRF-Token header
[$in, $err] = validate(input(), ['text' => 'required|max:500']); // input() also reads JSON bodies
if ($err) json(['errors' => $err], 422);
q('INSERT INTO notes (text) VALUES (?)', [$in['text']]);
json(['id' => (int) db()->lastInsertId()], 201);
}
json(['notes' => all('SELECT id, text FROM notes ORDER BY id DESC LIMIT 20')]);
Under /api (or with Accept: application/json) every error is JSON: {"error":404,"message":"Not Found"}.
Endpoints without CSRF
navigator.sendBeacon cannot send headers, and endpoints authorised by a one-time token or an API token don't use CSRF. Declare why:
csrf_exempt("sendBeacon: checked against the visit's one-time token");
It does nothing at runtime; it tells readers (and bin/ink check) that this is intended. Admin pages cannot be exempted.