Skip to content

2. Sign-in form

You will add a password field and a checkbox, and handle credentials that are well formed but wrong.

Try it: Mezzio ยท laminas-mvc

Assumes you have done chapter 0 and chapter 1.

shared/src/Login/LoginForm.php
<?php

declare(strict_types=1);

namespace App\Forms\Login;

use App\Forms\Csrf\AbstractCsrfProtectedForm;
use Laminas\Filter\StringTrim;
use Laminas\Form\Element\Checkbox;
use Laminas\Form\Element\Email;
use Laminas\Form\Element\Password;
use Laminas\Form\Element\Submit;
use Laminas\InputFilter\InputFilterProviderInterface;
use Laminas\Validator\NotEmpty;
use Override;

/**
 * Collects sign-in details without judging the password
 *
 * The password is neither filtered nor length checked: every character counts, and the rules for
 * choosing a password belong to registration.
 *
 * @api
 *
 * @extends AbstractCsrfProtectedForm<array<string, mixed>>
 */
final class LoginForm extends AbstractCsrfProtectedForm implements InputFilterProviderInterface
{
    public const string CREDENTIALS_REJECTED = 'The email address or password is incorrect';

    #[Override]
    public function getInputFilterSpecification(): array
    {
        return [
            'remember' => ['error_message' => 'Choose whether to stay signed in'],
            'email'    => [
                'required'      => true,
                'filters'       => [['name' => StringTrim::class]],
                'error_message' => 'Enter an email address in the format name@example.com',
            ],
            'password' => [
                'required'   => true,
                'validators' => [
                    [
                        'name'    => NotEmpty::class,
                        'options' => ['messages' => [NotEmpty::IS_EMPTY => 'Enter your password']],
                    ],
                ],
            ],
        ];
    }

    #[Override]
    public function init(): void
    {
        parent::init();

        $this->add([
            'name'       => 'email',
            'type'       => Email::class,
            'options'    => ['label' => 'Email address'],
            'attributes' => [
                'id'             => 'email',
                'required'       => true,
                'autocomplete'   => 'username',
                'autocapitalize' => 'none',
                'spellcheck'     => 'false',
            ],
        ]);

        $this->add([
            'name'       => 'password',
            'type'       => Password::class,
            'options'    => ['label' => 'Password'],
            'attributes' => ['id' => 'password', 'required' => true, 'autocomplete' => 'current-password'],
        ]);

        $this->add([
            'name'       => 'remember',
            'type'       => Checkbox::class,
            'options'    => ['label' => 'Keep me signed in'],
            'attributes' => ['id' => 'remember'],
        ]);

        $this->add([
            'name'       => 'signin',
            'type'       => Submit::class,
            'attributes' => ['value' => 'Sign in'],
        ]);
    }

    /**
     * Report a failed sign-in without revealing whether the account exists.
     */
    public function rejectCredentials(): void
    {
        $this->get('email')->setMessages([self::CREDENTIALS_REJECTED]);
    }
}

The form does not check credentials. The handler or controller asks a one-method interface:

shared/src/Login/CredentialCheckerInterface.php
<?php

declare(strict_types=1);

namespace App\Forms\Login;

use SensitiveParameter;

/** @api */
interface CredentialCheckerInterface
{
    public function check(string $email, #[SensitiveParameter] string $password): bool;
}

Bind it to your user storage. This stand-in lets you try the example as sam@example.com with the password correct horse battery staple:

shared/src/Login/DemoCredentialChecker.php
<?php

declare(strict_types=1);

namespace App\Forms\Login;

use Override;
use SensitiveParameter;

use function password_verify;
use function strcasecmp;

/**
 * Accepts a single hard-coded account, so that the example can be tried. Replace it with your user storage
 *
 * The password is "correct horse battery staple".
 *
 * @api
 */
final class DemoCredentialChecker implements CredentialCheckerInterface
{
    private const string EMAIL = 'sam@example.com';

    private const string PASSWORD_HASH = '$2y$12$.T9J2zh02yOnndJA31pmOOKKR6.Cv9a19ncH0PhbZuJ80RVdLrMLW';

    #[Override]
    public function check(string $email, #[SensitiveParameter] string $password): bool
    {
        // Always verify, so that response times do not reveal which accounts exist
        $matches = password_verify($password, self::PASSWORD_HASH);

        return $matches && 0 === strcasecmp($email, self::EMAIL);
    }
}

Mezzio

mezzio/src/App/Handler/LoginHandlerFactory.php
<?php

declare(strict_types=1);

namespace App\Handler;

use App\Forms\Login\CredentialCheckerInterface;
use Laminas\Form\FormElementManager;
use Mezzio\Template\TemplateRendererInterface;
use Psr\Container\ContainerInterface;

/** @api */
final class LoginHandlerFactory
{
    public function __invoke(ContainerInterface $container): LoginHandler
    {
        return new LoginHandler(
            $container->get(FormElementManager::class),
            $container->get(TemplateRendererInterface::class),
            $container->get(CredentialCheckerInterface::class),
        );
    }
}
mezzio/src/App/LoginConfigProvider.php
<?php

declare(strict_types=1);

namespace App;

use App\Forms\Login\CredentialCheckerInterface;
use App\Forms\Login\DemoCredentialChecker;
use App\Handler\LoginHandler;
use App\Handler\LoginHandlerFactory;
use Laminas\ServiceManager\Factory\InvokableFactory;

/** @api */
final class LoginConfigProvider
{
    /** @return array<string, mixed> */
    public function __invoke(): array
    {
        return [
            'dependencies' => [
                'aliases'   => [
                    CredentialCheckerInterface::class => DemoCredentialChecker::class,
                ],
                'factories' => [
                    DemoCredentialChecker::class => InvokableFactory::class,
                    LoginHandler::class          => LoginHandlerFactory::class,
                ],
            ],
        ];
    }
}

Add the provider to config/config.php, and register the route:

mezzio/config/routes/login.php
<?php

declare(strict_types=1);

use App\Handler\LoginHandler;
use Mezzio\Application;

return static function (Application $app): void {
    $app->route('/login', LoginHandler::class, ['GET', 'POST'], 'login');
};

laminas-mvc

mvc/module/Application/src/Controller/LoginControllerFactory.php
<?php

declare(strict_types=1);

namespace Application\Controller;

use App\Forms\Csrf\CsrfGuardInterface;
use App\Forms\Login\CredentialCheckerInterface;
use Laminas\Form\FormElementManager;
use Psr\Container\ContainerInterface;

/** @api */
final class LoginControllerFactory
{
    public function __invoke(ContainerInterface $container): LoginController
    {
        return new LoginController(
            $container->get(FormElementManager::class),
            $container->get(CsrfGuardInterface::class),
            $container->get(CredentialCheckerInterface::class),
        );
    }
}

Merge this file into your module configuration, as Module does in chapter 0:

mvc/module/Application/config/login.config.php
<?php

declare(strict_types=1);

namespace Application;

use App\Forms\Login\CredentialCheckerInterface;
use App\Forms\Login\DemoCredentialChecker;
use Laminas\Router\Http\Literal;
use Laminas\ServiceManager\Factory\InvokableFactory;

return [
    'router'          => [
        'routes' => [
            'login' => [
                'type'    => Literal::class,
                'options' => [
                    'route'    => '/login',
                    'defaults' => ['controller' => Controller\LoginController::class, 'action' => 'form'],
                ],
            ],
        ],
    ],
    'controllers'     => [
        'factories' => [
            Controller\LoginController::class => Controller\LoginControllerFactory::class,
        ],
    ],
    'service_manager' => [
        'aliases'   => [
            CredentialCheckerInterface::class => DemoCredentialChecker::class,
        ],
        'factories' => [
            DemoCredentialChecker::class => InvokableFactory::class,
        ],
    ],
    'view_manager'    => [
        'template_map' => [
            'forms::login' => __DIR__ . '/../../../vendor/laminas-howto/forms-shared/templates/login.phtml',
        ],
    ],
];
shared/templates/login.phtml
<?php

declare(strict_types=1);

/**
 * @var Laminas\View\Renderer\PhpRenderer $this
 * @var App\Forms\Login\LoginForm $form
 * @var string|null $status
 */

$form->prepare();
$this->headTitle($form->getMessages() === [] ? 'Sign in' : 'Error: Sign in', 'SET');
?>
<?= $this->partial('forms::error-summary', ['form' => $form]) ?>

<h1>Sign in</h1>

<?php if ($status !== null): ?>
    <p role="status" tabindex="-1" autofocus><?= $this->escapeHtml($status) ?></p>
<?php endif; ?>

<?= $this->form()->openTag($form) ?>
    <?= $this->formElement($form->get('csrf')) ?>
    <?= $this->partial('forms::field', ['element' => $form->get('email')]) ?>
    <?= $this->partial('forms::field', ['element' => $form->get('password')]) ?>
    <?= $this->partial('forms::checkbox', ['element' => $form->get('remember')]) ?>
    <?= $this->formElement($form->get('signin')) ?>
<?= $this->form()->closeTag() ?>

A checkbox needs its own partial, with the control before its label:

shared/templates/checkbox.phtml
<?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>
mezzio/src/App/Handler/LoginHandler.php
<?php

declare(strict_types=1);

namespace App\Handler;

use App\Csrf\MezzioCsrfGuard;
use App\Forms\Login\CredentialCheckerInterface;
use App\Forms\Login\LoginForm;
use Laminas\Diactoros\Response\HtmlResponse;
use Laminas\Diactoros\Response\RedirectResponse;
use Laminas\Form\FormElementManager;
use Mezzio\Csrf\CsrfGuardInterface;
use Mezzio\Csrf\CsrfMiddleware;
use Mezzio\Flash\FlashMessageMiddleware;
use Mezzio\Flash\FlashMessagesInterface;
use Mezzio\Template\TemplateRendererInterface;
use Override;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;

/** @api */
final readonly class LoginHandler implements RequestHandlerInterface
{
    public function __construct(
        private FormElementManager $forms,
        private TemplateRendererInterface $renderer,
        private CredentialCheckerInterface $credentials,
    ) {}

    #[Override]
    public function handle(ServerRequestInterface $request): ResponseInterface
    {
        /** @var CsrfGuardInterface $guard */
        $guard = $request->getAttribute(CsrfMiddleware::GUARD_ATTRIBUTE);
        /** @var FlashMessagesInterface $flash */
        $flash = $request->getAttribute(FlashMessageMiddleware::FLASH_ATTRIBUTE);

        $form = $this->forms->get(LoginForm::class);
        $form->setCsrfGuard(new MezzioCsrfGuard($guard));

        if ($request->getMethod() === 'POST') {
            /** @var array<string, mixed> $post */
            $post = $request->getParsedBody();
            $form->setData($post);

            if ($form->isValid()) {
                /** @var array{email: string, password: string, remember: string} $data */
                $data = $form->getData();

                // Limit repeated attempts here, per account and per IP address
                if ($this->credentials->check($data['email'], $data['password'])) {
                    // Regenerate the session ID, then sign the user in. Honour $data['remember'] here
                    $flash->flash('status', 'You are signed in.');

                    return new RedirectResponse('/login', 303);
                }

                $form->rejectCredentials();
            }
        }

        return new HtmlResponse($this->renderer->render('forms::login', [
            'form'   => $form,
            'status' => $flash->getFlash('status'),
        ]));
    }
}
mvc/module/Application/src/Controller/LoginController.php
<?php

declare(strict_types=1);

namespace Application\Controller;

use App\Forms\Csrf\CsrfGuardInterface;
use App\Forms\Login\CredentialCheckerInterface;
use App\Forms\Login\LoginForm;
use Laminas\Form\FormElementManager;
use Laminas\Http\Request;
use Laminas\Http\Response;
use Laminas\Mvc\Controller\AbstractActionController;
use Laminas\Mvc\Plugin\FlashMessenger\FlashMessenger;
use Laminas\Stdlib\Parameters;
use Laminas\View\Model\ViewModel;

/** @api */
final class LoginController extends AbstractActionController
{
    public function __construct(
        private readonly FormElementManager $forms,
        private readonly CsrfGuardInterface $guard,
        private readonly CredentialCheckerInterface $credentials,
    ) {}

    public function formAction(): Response|ViewModel
    {
        $form = $this->forms->get(LoginForm::class);
        $form->setCsrfGuard($this->guard);

        /** @var Request $request */
        $request = $this->getRequest();
        /** @var FlashMessenger $flash */
        $flash = $this->plugin('flashMessenger');

        if ($request->isPost()) {
            /** @var Parameters $post */
            $post = $request->getPost();
            $form->setData($post->toArray());

            if ($form->isValid()) {
                /** @var array{email: string, password: string, remember: string} $data */
                $data = $form->getData();

                // Limit repeated attempts here, per account and per IP address
                if ($this->credentials->check($data['email'], $data['password'])) {
                    // Regenerate the session ID, then sign the user in. Honour $data['remember'] here
                    $flash->addSuccessMessage('You are signed in.');

                    return $this->redirect()->toRoute('login')->setStatusCode(303);
                }

                $form->rejectCredentials();
            }
        }

        $view = new ViewModel([
            'form'   => $form,
            'status' => $flash->getSuccessMessages()[0] ?? null,
        ]);

        return $view->setTemplate('forms::login');
    }
}

How it works

Two kinds of failure. The input filter rejects input that cannot be right, such as a missing password. Only valid input reaches your credential check, and rejectCredentials() puts a failure back on the form, so it appears in the same error summary.

One message for both mistakes. Saying "no such account" tells a stranger who has an account. The demo checker also verifies a password even when the account is unknown, so the two cases take a similar time. Do the same in yours.

Leave the password alone. No StringTrim and no length rule: spaces may be part of it, and an old password must keep working when your rules change. Store only hashes made with password_hash().

The password is never sent back. The Password element empties itself when the form is prepared, while the email address stays filled in.

Help password managers. autocomplete="username" and autocomplete="current-password" let browsers fill both fields, and nothing blocks pasting. This helps you meet WCAG 2.2 "Accessible Authentication".

An unticked box sends nothing. The Checkbox element renders a hidden field first, so you always receive '1' or '0'.

Before you use this for real

The comments in the handler and controller mark the work this example leaves out:

  • Limit repeated attempts, per account and per IP address.
  • Regenerate the session ID when someone signs in, to prevent session fixation.
  • Honour "Keep me signed in".
  • Serve the page over HTTPS and mark the session cookie Secure. See Set up sessions.

Further opportunities

None of these are built or tested here. Add the ones your site needs.

Opportunity Where How
Go beyond a basic attempt limit Credential checker or middleware Add growing delays or a short lock. Take care that an attacker cannot lock other people out
Restrict by IP address Middleware or dispatch listener Useful for administration areas. Behind a proxy, trust X-Forwarded-For only when your own proxy set it
Add a second factor After the credentials are accepted, before signing in Ask for a one-time code on a second page
Offer passkeys A separate WebAuthn flow Add webauthn to the autocomplete value of the email field
Upgrade old hashes Credential checker After a successful check, use password_needs_rehash() and save a new hash
Remember people safely Where the "Honour $data['remember']" comment is Issue a random, long-lived token, store only its hash, and revoke it when the password changes
Keep an audit trail Handler or controller Record time, address and outcome, never the password
Warn about unfamiliar sign-ins After signing in Email the account holder when a new device is used
Return to the requested page Handler or controller The examples redirect to a fixed route. If you take a "return to" value from the request, accept only paths on your own site
Skip the form when signed in Before the form is created Redirect people who already have a session
Let people see what they type Template and a little JavaScript Add a "Show password" button that switches the input type

Common mistakes

  • Using autocomplete="off", which gets in the way of password managers.
  • Setting maxlength on the password field, which silently cuts off a pasted password.
  • Logging the submitted data. Mark password parameters with #[SensitiveParameter] to keep them out of stack traces.