0. Wire up laminas-form
Assumes you have a working Mezzio or laminas-mvc application on PHP 8.4 with the intl extension. The form view helpers need laminas-i18n, which needs intl.
Install
#!/usr/bin/env bash
set -euo pipefail
composer require --with-all-dependencies \
laminas/laminas-form:^3.25 \
laminas/laminas-hydrator:^4.16 \
laminas/laminas-i18n:^2.33 \
laminas/laminas-uri:^2.13 \
laminas/laminas-view:^2.44 \
mezzio/mezzio-csrf:^1.12 \
mezzio/mezzio-flash:^1.11 \
mezzio/mezzio-laminasviewrenderer:^2.19 \
mezzio/mezzio-session-ext:^1.22 \
"$@"
#!/usr/bin/env bash
set -euo pipefail
composer require --with-all-dependencies \
laminas/laminas-form:^3.25 \
laminas/laminas-hydrator:^4.16 \
laminas/laminas-i18n:^2.33 \
laminas/laminas-mvc-plugin-flashmessenger:^1.11 \
laminas/laminas-session:^2.27 \
laminas/laminas-uri:^2.13 \
laminas/laminas-view:^2.44 \
"$@"
laminas-hydrator and laminas-uri are first needed in chapter 4, to bind objects and to check web addresses.
In the current Mezzio skeleton this downgrades mezzio-template from 3 to 2, which mezzio-laminasviewrenderer 2 needs. The newest laminas-mvc-skeleton (2.4.0) does not accept PHP 8.4, so these steps assume an existing MVC application.
Composer may warn that laminas-json is abandoned, and for MVC also laminas-config and laminas-loader. They are required by the libraries above.
Where the files go
The examples keep the forms in a separate package so that both applications can load the same code. In your own application you can copy them straight in:
| In this repository | In your application |
|---|---|
examples/forms/shared/src/ |
Any PSR-4 autoloaded directory. The classes use the App\Forms namespace, so in the Mezzio skeleton, src/App/Forms/ works as it is. Elsewhere, change the namespace to your own |
examples/forms/shared/templates/ |
Your template directory. Change the vendor/laminas-howto/forms-shared/templates paths in the configuration to match |
Keep the template names, such as forms::field and forms::error-summary, which the templates and handlers use.
Register the components
The shared settings are set up here. Each later chapter then adds its own configuration file, so you can see exactly what one form needs. If you would rather keep a single ConfigProvider or module.config.php, copy the entries into it.
<?php
declare(strict_types=1);
use Laminas\ConfigAggregator\ConfigAggregator;
return new ConfigAggregator([
Laminas\Diactoros\ConfigProvider::class,
Laminas\Filter\ConfigProvider::class,
Laminas\Form\ConfigProvider::class,
Laminas\HttpHandlerRunner\ConfigProvider::class,
Laminas\Hydrator\ConfigProvider::class,
Laminas\I18n\ConfigProvider::class,
Laminas\InputFilter\ConfigProvider::class,
Laminas\Validator\ConfigProvider::class,
Mezzio\ConfigProvider::class,
Mezzio\Csrf\ConfigProvider::class,
Mezzio\Flash\ConfigProvider::class,
Mezzio\Helper\ConfigProvider::class,
Mezzio\LaminasView\ConfigProvider::class,
Mezzio\Router\ConfigProvider::class,
Mezzio\Router\FastRouteRouter\ConfigProvider::class,
Mezzio\Session\ConfigProvider::class,
Mezzio\Session\Ext\ConfigProvider::class,
App\ConfigProvider::class,
App\AvatarConfigProvider::class,
App\ContactConfigProvider::class,
App\HelloConfigProvider::class,
App\LoginConfigProvider::class,
App\OrderConfigProvider::class,
App\PasswordConfigProvider::class,
App\ProfileConfigProvider::class,
App\RegisterConfigProvider::class,
App\SearchConfigProvider::class,
])->getMergedConfig();
<?php
declare(strict_types=1);
namespace App;
/**
* Settings every form needs. Each example adds its own provider
*
* @api
*/
final class ConfigProvider
{
/** @return array<string, mixed> */
public function __invoke(): array
{
return [
'view_helper_config' => ['doctype' => 'HTML5'],
'session' => [
'cookie_httponly' => true,
'cookie_samesite' => 'Lax',
],
'templates' => [
'layout' => 'layout::default',
'paths' => [
'demo' => [__DIR__ . '/../../vendor/laminas-howto/forms-shared/demo'],
'error' => [__DIR__ . '/../../templates/error'],
'forms' => [__DIR__ . '/../../vendor/laminas-howto/forms-shared/templates'],
'layout' => [__DIR__ . '/../../templates/layout'],
],
],
];
}
}
<?php
declare(strict_types=1);
use Laminas\Stratigility\Middleware\ErrorHandler;
use Mezzio\Application;
use Mezzio\Csrf\CsrfMiddleware;
use Mezzio\Flash\FlashMessageMiddleware;
use Mezzio\Handler\NotFoundHandler;
use Mezzio\Router\Middleware\DispatchMiddleware;
use Mezzio\Router\Middleware\ImplicitHeadMiddleware;
use Mezzio\Router\Middleware\MethodNotAllowedMiddleware;
use Mezzio\Router\Middleware\RouteMiddleware;
use Mezzio\Session\SessionMiddleware;
return static function (Application $app): void {
$app->pipe(ErrorHandler::class);
$app->pipe(SessionMiddleware::class);
$app->pipe(FlashMessageMiddleware::class);
$app->pipe(CsrfMiddleware::class);
$app->pipe(RouteMiddleware::class);
// Answers HEAD for GET routes, and 405 when a path exists but not for this method
$app->pipe(ImplicitHeadMiddleware::class);
$app->pipe(MethodNotAllowedMiddleware::class);
$app->pipe(DispatchMiddleware::class);
$app->pipe(NotFoundHandler::class);
};
<?php
declare(strict_types=1);
use Mezzio\Application;
return static function (Application $app): void {
foreach ([
'hello',
'contact',
'login',
'register',
'profile',
'password',
'order',
'avatar',
'search',
] as $example) {
/** @var Closure(Application): void $routes */
$routes = require __DIR__ . "/routes/{$example}.php";
$routes($app);
}
};
<?php
declare(strict_types=1);
return [
'modules' => [
'Laminas\Filter',
'Laminas\Form',
'Laminas\Hydrator',
'Laminas\I18n',
'Laminas\InputFilter',
'Laminas\Mvc\Plugin\FlashMessenger',
'Laminas\Router',
'Laminas\Session',
'Laminas\Validator',
'Application',
],
'module_listener_options' => [
'config_glob_paths' => [],
'module_paths' => [__DIR__ . '/../module', __DIR__ . '/../vendor'],
],
];
<?php
declare(strict_types=1);
namespace Application;
use App\Forms\Csrf\CsrfGuardInterface;
use Laminas\Session\Storage\SessionArrayStorage;
return [
'service_manager' => [
'factories' => [
CsrfGuardInterface::class => Csrf\SessionCsrfGuardFactory::class,
],
],
'session_config' => [
'cookie_httponly' => true,
'cookie_samesite' => 'Lax',
],
'session_storage' => [
'type' => SessionArrayStorage::class,
],
'view_manager' => [
'doctype' => 'HTML5',
'not_found_template' => 'error/404',
'exception_template' => 'error/index',
'template_map' => [
'layout/layout' => __DIR__ . '/../view/layout/layout.phtml',
'error/404' => __DIR__ . '/../view/error/404.phtml',
'error/index' => __DIR__ . '/../view/error/index.phtml',
'demo::intro' => __DIR__ . '/../../../vendor/laminas-howto/forms-shared/demo/intro.phtml',
'forms::checkbox' => __DIR__ . '/../../../vendor/laminas-howto/forms-shared/templates/checkbox.phtml',
'forms::error-summary' =>
__DIR__ . '/../../../vendor/laminas-howto/forms-shared/templates/error-summary.phtml',
'forms::field' => __DIR__ . '/../../../vendor/laminas-howto/forms-shared/templates/field.phtml',
],
],
];
<?php
declare(strict_types=1);
namespace Application;
use Laminas\Stdlib\ArrayUtils;
/** @api */
final class Module
{
/** @return array<array-key, mixed> */
public function getConfig(): array
{
$config = [];
// The shared settings first, then one file for each example
foreach ([
'module',
'hello',
'contact',
'login',
'register',
'profile',
'password',
'order',
'avatar',
'search',
] as $name) {
/** @var array<array-key, mixed> $part */
$part = require __DIR__ . "/../config/{$name}.config.php";
$config = ArrayUtils::merge($config, $part);
}
return $config;
}
}
Starting from the Mezzio skeleton? Merge these listings into the files it gave you, and do not replace them. In config/pipeline.php, add the session, flash and CSRF lines after ErrorHandler and leave the skeleton's other middleware, such as the URL helper, where it is. In src/App/ConfigProvider.php, add the view_helper_config and session settings, the layout name and the forms template path to what is already there. Point the forms path at the directory where you copied the templates, and leave out the demo path.
Tell laminas-view the page is HTML5. The layout's <!DOCTYPE html> is not enough. Without the doctype setting, the view helpers write older markup, including action="" on forms, which HTML5 does not allow, and required="required". Mezzio reads it from view_helper_config, and laminas-mvc from view_manager.
In Mezzio the order matters: session first, then flash messages and CSRF. See Set up sessions.
The demo template path and demo::intro template print the note at the top of each running example. Leave them, and the matching line in the layout, out of your own application.
Protect forms against CSRF
laminas-form has a Csrf element, but the validator behind it is deprecated. These examples use a small element of their own, and ask each framework only to create and check a token.
Each form class has its own token, so opening the sign-in page does not expire a contact form left open elsewhere. A token works once: if the same form is open in two tabs, only the newer one can be submitted, and the older one asks the visitor to submit again.
Shared by both frameworks
<?php
declare(strict_types=1);
namespace App\Forms\Csrf;
use SensitiveParameter;
/**
* The only thing a shared form needs from a framework to protect itself against CSRF
*
* @api
*/
interface CsrfGuardInterface
{
/**
* Create a token and remember it for the next submission of the form identified by $key.
*/
public function generate(string $key): string;
/**
* Check a token submitted by the form identified by $key. A token can only be checked once.
*/
public function validate(string $key, #[SensitiveParameter] string $token): bool;
}
<?php
declare(strict_types=1);
namespace App\Forms\Csrf;
use Laminas\Form\Element;
use Laminas\InputFilter\InputProviderInterface;
use LogicException;
use Override;
/**
* Hidden field that always renders a fresh token, ignoring whatever was submitted
*
* A guard must be set before the form is rendered or validated.
*
* @api
*/
final class CsrfElement extends Element implements InputProviderInterface
{
/** @var array<string, scalar|null> */
protected $attributes = ['type' => 'hidden'];
private ?CsrfGuardInterface $guard = null;
private string $key = '';
private ?string $token = null;
/** @return array{name: string, required: true, error_message: string, validators: list<CsrfValidator>} */
#[Override]
public function getInputSpecification(): array
{
return [
'name' => (string) $this->getName(),
'required' => true,
'error_message' => CsrfValidator::MESSAGE,
'validators' => [new CsrfValidator($this->guard(), $this->key)],
];
}
#[Override]
public function getValue(): string
{
return $this->token ??= $this->guard()->generate($this->key);
}
/** @param string $key Identifies the form, so that forms do not replace each other's tokens */
public function setGuard(CsrfGuardInterface $guard, string $key): void
{
$this->guard = $guard;
$this->key = $key;
$this->token = null;
}
/** @throws LogicException If no guard has been set. */
private function guard(): CsrfGuardInterface
{
return $this->guard ?? throw new LogicException('Call setCsrfGuard() on the form before using it');
}
}
<?php
declare(strict_types=1);
namespace App\Forms\Csrf;
use Laminas\Validator\AbstractValidator;
use Override;
use function is_string;
/** @api */
final class CsrfValidator extends AbstractValidator
{
public const string INVALID = 'csrfInvalid';
public const string MESSAGE = 'This form has expired. Please submit it again.';
/**
* @mago-expect analysis:missing-property-type The parent declares this property without a type
*
* @var array<string, string>
*/
protected $messageTemplates = [
self::INVALID => self::MESSAGE,
];
public function __construct(
private readonly CsrfGuardInterface $guard,
private readonly string $key,
) {
parent::__construct();
}
#[Override]
public function isValid(mixed $value): bool
{
if (is_string($value) && $this->guard->validate($this->key, $value)) {
return true;
}
$this->error(self::INVALID);
return false;
}
}
<?php
declare(strict_types=1);
namespace App\Forms\Csrf;
use Laminas\Form\Element\Captcha;
use Laminas\Form\Element\File;
use Laminas\Form\Element\MonthSelect;
use Laminas\Form\Element\MultiCheckbox;
use Laminas\Form\Element\Radio;
use Laminas\Form\Element\Select;
use Laminas\Form\ElementInterface;
use Laminas\Form\Form;
use LogicException;
use Override;
use Traversable;
use function array_is_list;
use function is_array;
use function iterator_to_array;
/**
* Base class for forms submitted with POST
*
* Subclasses must call parent::init(). A list sent to a field that takes one value is treated as
* not sent, because the page cannot redisplay it and the code reading it expects one value. Fields
* inside fieldsets are not checked.
*
* @api
*
* @template TData
*
* @extends Form<TData>
*/
abstract class AbstractCsrfProtectedForm extends Form
{
#[Override]
public function init(): void
{
$this->add([
'name' => 'csrf',
'type' => CsrfElement::class,
]);
}
/** @throws LogicException If the csrf element has been replaced by another type. */
public function setCsrfGuard(CsrfGuardInterface $guard): void
{
$element = $this->get('csrf');
if (! $element instanceof CsrfElement) {
throw new LogicException('The csrf element is missing');
}
$element->setGuard($guard, static::class);
}
/** @param iterable<mixed, mixed> $data */
#[Override]
public function setData(iterable $data): static
{
$data = $data instanceof Traversable ? iterator_to_array($data) : $data;
foreach ($this->getElements() as $element) {
$name = (string) $element->getName();
/** @var mixed $value */
$value = $data[$name] ?? null;
if (! is_array($value) || $this->takesList($element, $value)) {
continue;
}
unset($data[$name]);
}
parent::setData($data);
return $this;
}
/** @param array<array-key, mixed> $value */
private function takesList(ElementInterface $element, array $value): bool
{
$multiple = (bool) $element->getAttribute('multiple');
// One file from $_FILES is itself an array, so only a list means several files
if ($element instanceof File) {
return $multiple || ! array_is_list($value);
}
// Radio buttons extend MultiCheckbox, but only one of them can be chosen
if ($element instanceof MultiCheckbox) {
return ! $element instanceof Radio;
}
return (
$element instanceof Captcha || $element instanceof MonthSelect || $element instanceof Select && $multiple
);
}
}
Lists where one value belongs. A request can send name[]=x where a field expects text. laminas-form cannot print that back, so the page fails or shows "Array". The base form treats such a value as not sent, and a required field shows its usual message. Checkbox groups, multiple selects, fields for several files, CAPTCHAs and date selects still receive lists. A field for one file still accepts the array PHP uses to describe it. Fields inside fieldsets are not checked, so tidy those yourself, as chapter 6 does. A form that does not extend this class needs the same care, as the search form in chapter 8 shows.
Framework adapter
<?php
declare(strict_types=1);
namespace App\Csrf;
use App\Forms\Csrf\CsrfGuardInterface;
use Mezzio\Csrf\CsrfGuardInterface as MezzioGuardInterface;
use Override;
use SensitiveParameter;
/** @api */
final readonly class MezzioCsrfGuard implements CsrfGuardInterface
{
public function __construct(
private MezzioGuardInterface $guard,
) {}
#[Override]
public function generate(string $key): string
{
return $this->guard->generateToken("__csrf.{$key}");
}
#[Override]
public function validate(string $key, #[SensitiveParameter] string $token): bool
{
return $this->guard->validateToken($token, "__csrf.{$key}");
}
}
<?php
declare(strict_types=1);
namespace Application\Csrf;
use App\Forms\Csrf\CsrfGuardInterface;
use Laminas\Session\Container;
use Override;
use SensitiveParameter;
use function bin2hex;
use function hash_equals;
use function is_string;
use function random_bytes;
/** @api */
final readonly class SessionCsrfGuard implements CsrfGuardInterface
{
public function __construct(
private Container $session,
) {}
#[Override]
public function generate(string $key): string
{
$token = bin2hex(random_bytes(32));
$this->session->offsetSet($key, $token);
return $token;
}
#[Override]
public function validate(string $key, #[SensitiveParameter] string $token): bool
{
/** @var mixed $expected */
$expected = $this->session->offsetGet($key);
$this->session->offsetUnset($key);
return is_string($expected) && hash_equals($expected, $token);
}
}
<?php
declare(strict_types=1);
namespace Application\Csrf;
use Laminas\Session\Container;
use Laminas\Session\ManagerInterface;
use Psr\Container\ContainerInterface;
/** @api */
final class SessionCsrfGuardFactory
{
public function __invoke(ContainerInterface $container): SessionCsrfGuard
{
return new SessionCsrfGuard(new Container('csrf', $container->get(ManagerInterface::class)));
}
}
Add the stylesheet
Copy the compiled CSS and link it from your layout, as described in Styling forms.
Accessible field and error templates
Forms reuse these partials. The checkbox partial is first needed in chapter 2.
<?php
declare(strict_types=1);
/**
* @var Laminas\View\Renderer\PhpRenderer $this
* @var Laminas\Form\ElementInterface $element
*/
$id = (string) $element->getAttribute('id');
$hint = $element->getOption('hint');
$hasErrors = $element->getMessages() !== [];
$describedBy = [];
if ($hint !== null) {
$describedBy[] = $id . '-hint';
}
if ($hasErrors) {
$describedBy[] = $id . '-error';
$element->setAttribute('aria-invalid', 'true');
}
if ($describedBy !== []) {
$element->setAttribute('aria-describedby', implode(' ', $describedBy));
}
?>
<div class="field">
<?= $this->formLabel($element) ?>
<?php if ($hint !== null): ?>
<p class="hint" id="<?= $this->escapeHtmlAttr($id) ?>-hint"><?= $this->escapeHtml($hint) ?></p>
<?php endif; ?>
<?= $this->formElementErrors($element, ['class' => 'error', 'id' => $id . '-error']) ?>
<?= $this->formElement($element) ?>
</div>
<?php
declare(strict_types=1);
use Laminas\Form\FieldsetInterface;
/**
* @var Laminas\View\Renderer\PhpRenderer $this
* @var Laminas\Form\FormInterface $form
*/
if ($form->getMessages() === []) {
return;
}
// Messages are nested the way the fields are, so follow each fieldset down to its elements
$errors = [];
$collect = static function (FieldsetInterface $fieldset, array $messages, string $context) use (&$collect, &$errors): void {
foreach ($messages as $name => $found) {
$element = $fieldset->get((string) $name);
if ($element instanceof FieldsetInterface) {
$label = (string) $element->getLabel();
$collect($element, $found, $label === '' ? $context : $context . $label . ': ');
continue;
}
foreach ($found as $message) {
$errors[] = [$element, $context . $message];
}
}
};
$collect($form, $form->getMessages(), '');
?>
<div class="error-summary" role="alert" tabindex="-1" autofocus aria-labelledby="error-summary-title">
<h2 id="error-summary-title">There is a problem</h2>
<ul>
<?php foreach ($errors as [$element, $message]): ?>
<li>
<?php if ($element->getAttribute('type') === 'hidden'): ?>
<?= $this->escapeHtml($message) ?>
<?php else: ?>
<a href="#<?= $this->escapeHtmlAttr($element->getAttribute('id')) ?>"><?= $this->escapeHtml($message) ?></a>
<?php endif; ?>
</li>
<?php endforeach; ?>
</ul>
</div>
<?php
declare(strict_types=1);
/**
* @var Laminas\View\Renderer\PhpRenderer $this
* @var Laminas\Form\Element\Checkbox $element
*/
$id = (string) $element->getAttribute('id');
if ($element->getMessages() !== []) {
$element->setAttribute('aria-invalid', 'true');
$element->setAttribute('aria-describedby', $id . '-error');
}
?>
<div class="field checkbox">
<?= $this->formElementErrors($element, ['class' => 'error', 'id' => $id . '-error']) ?>
<?= $this->formElement($element) ?>
<?= $this->formLabel($element) ?>
</div>