Documentation · Chapter 04

Protect the form
in layers.

Security is not one function. It combines request intent, validation, escaping, and automatic framework protections.

We continue the reading-list project. Data will be kept in the session before introducing a database.

CSRF: prevent another page from acting as you

A CSRF attack attempts to make your browser submit an action you did not choose. PHPAML associates a secret token with your session. The form submits it and middleware checks it before allowing POST.

phpaml — zsh
<form method="post" action="/books">
    <?= $view->csrfField() ?>
    <!-- champs -->
</form>

In a current classic application, CsrfMiddleware is added automatically. A missing or invalid token receives 419. Do not disable this protection to fix a form: add the expected field.

Validation and escaping solve different problems

VALIDATION

Decides whether a value is acceptable for your application: length, type, presence, format.

ESCAPING

Prevents a displayed value from being interpreted as an HTML tag or script.

phpaml — zsh
<?= $view->escape($book['title']) ?>

Protections already active

CSRF

Checks modifying requests.

Rate limiting

Slows repeated POST, PUT, PATCH, and DELETE submissions.

Security headers

Harden browser behavior.

Internal redirects

Response rejects external or malformed destinations.

Simple security test

  1. Submit the form normally: it should succeed.
  2. Inspect the page and temporarily remove the _token field.
  3. Submit again: PHPAML should return 419.
  4. Restore csrfField() and verify success.
Never log the token

A CSRF token is a security value tied to a session. Do not display it in a public error or copy it into a report.