7. Photo upload
You will build a form that takes a new profile photo, checks what is really in the file, and explains any problem.
Try it: Mezzio ยท laminas-mvc
Assumes you have done chapter 0. PHP needs the fileinfo extension.
<?php
declare(strict_types=1);
namespace App\Forms\Avatar;
use App\Forms\Csrf\AbstractCsrfProtectedForm;
use Laminas\Form\Element\File;
use Laminas\Form\Element\Submit;
use Laminas\InputFilter\FileInput;
use Laminas\InputFilter\InputFilterProviderInterface;
use Laminas\Validator\File\ImageSize;
use Laminas\Validator\File\MimeType;
use Laminas\Validator\File\Size;
use Laminas\Validator\File\UploadFile;
use Override;
use function array_is_list;
use function is_array;
/**
* Uploads one profile photo
*
* Give it each request through setSubmission(), which takes the photo from the uploaded files only.
* The fileinfo extension reads the type of the file from its contents.
*
* @api
*
* @extends AbstractCsrfProtectedForm<array<string, mixed>>
*/
final class AvatarForm extends AbstractCsrfProtectedForm implements InputFilterProviderInterface
{
private const string CHOOSE = 'Choose an image to upload';
private const string FAILED = 'The image could not be received. Try again later';
private const string TOO_LARGE = 'The image must be 1MB or smaller';
private const string UNREADABLE = 'The image could not be read. Choose another';
#[Override]
public function getInputFilterSpecification(): array
{
return [
'avatar' => [
'type' => FileInput::class,
'required' => true,
'validators' => [
// Listed first so that these messages replace the ones FileInput would add
[
'name' => UploadFile::class,
'break_chain_on_failure' => true,
'options' => [
'messages' => [
UploadFile::NO_FILE => self::CHOOSE,
UploadFile::ATTACK => self::CHOOSE,
UploadFile::FILE_NOT_FOUND => self::CHOOSE,
UploadFile::INI_SIZE => self::TOO_LARGE,
UploadFile::FORM_SIZE => self::TOO_LARGE,
UploadFile::PARTIAL => 'The upload was interrupted. Choose the image again',
UploadFile::NO_TMP_DIR => self::FAILED,
UploadFile::CANT_WRITE => self::FAILED,
UploadFile::EXTENSION => self::FAILED,
UploadFile::UNKNOWN => self::FAILED,
],
],
],
[
'name' => Size::class,
'break_chain_on_failure' => true,
'options' => [
'max' => '1MB',
'messages' => [
Size::TOO_BIG => self::TOO_LARGE,
Size::NOT_FOUND => self::UNREADABLE,
],
],
],
// Reads the contents. The file name and the type sent by the browser prove nothing
[
'name' => MimeType::class,
'break_chain_on_failure' => true,
'options' => [
'mimeType' => ['image/jpeg', 'image/png', 'image/webp'],
'messages' => [
MimeType::FALSE_TYPE => 'Choose a JPEG, PNG or WebP image',
MimeType::NOT_DETECTED => self::UNREADABLE,
MimeType::NOT_READABLE => self::UNREADABLE,
],
],
],
[
'name' => ImageSize::class,
'options' => [
'minWidth' => 100,
'minHeight' => 100,
'maxWidth' => 4000,
'maxHeight' => 4000,
'messages' => [
ImageSize::WIDTH_TOO_SMALL => 'The image must be at least %minwidth% pixels wide',
ImageSize::WIDTH_TOO_BIG => 'The image must be %maxwidth% pixels wide or less',
ImageSize::HEIGHT_TOO_SMALL => 'The image must be at least %minheight% pixels tall',
ImageSize::HEIGHT_TOO_BIG => 'The image must be %maxheight% pixels tall or less',
ImageSize::NOT_DETECTED => self::UNREADABLE,
ImageSize::NOT_READABLE => self::UNREADABLE,
],
],
],
],
],
];
}
#[Override]
public function init(): void
{
parent::init();
$this->add([
'name' => 'avatar',
'type' => File::class,
'options' => [
'label' => 'Profile photo',
'hint' => 'JPEG, PNG or WebP, up to 1MB, and between 100 and 4000 pixels on each side.',
],
'attributes' => [
'id' => 'avatar',
'accept' => 'image/jpeg,image/png,image/webp',
'required' => true,
],
]);
$this->add([
'name' => 'upload',
'type' => Submit::class,
'attributes' => ['value' => 'Upload photo'],
]);
}
/**
* @param array<array-key, mixed> $fields The posted fields
* @param array<array-key, mixed> $files The uploaded files, as PSR-7 objects or in the shape of $_FILES
* @return bool False if PHP dropped the request for being too large, which leaves nothing to validate
*/
public function setSubmission(array $fields, array $files): bool
{
// PHP empties both when a request is larger than post_max_size
if ([] === $fields && [] === $files) {
$this->get('avatar')->setMessages([self::TOO_LARGE]);
return false;
}
/** @var mixed $file */
$file = $files['avatar'] ?? '';
// Always replaced, so a posted field cannot pose as an upload. '' is reported as nothing chosen
$fields['avatar'] = is_array($file) && array_is_list($file) ? '' : $file;
$this->setData($fields);
return true;
}
}
The form needs no factory. FormElementManager creates it and calls init().
Mezzio
<?php
declare(strict_types=1);
namespace App\Handler;
use Laminas\Form\FormElementManager;
use Mezzio\Template\TemplateRendererInterface;
use Psr\Container\ContainerInterface;
/** @api */
final class AvatarHandlerFactory
{
public function __invoke(ContainerInterface $container): AvatarHandler
{
return new AvatarHandler(
$container->get(FormElementManager::class),
$container->get(TemplateRendererInterface::class),
);
}
}
<?php
declare(strict_types=1);
namespace App;
use App\Handler\AvatarHandler;
use App\Handler\AvatarHandlerFactory;
/** @api */
final class AvatarConfigProvider
{
/** @return array<string, mixed> */
public function __invoke(): array
{
return [
'dependencies' => [
'factories' => [
AvatarHandler::class => AvatarHandlerFactory::class,
],
],
];
}
}
Add the provider to config/config.php, and register the route:
<?php
declare(strict_types=1);
use App\Handler\AvatarHandler;
use Mezzio\Application;
return static function (Application $app): void {
$app->route('/avatar', AvatarHandler::class, ['GET', 'POST'], 'avatar');
};
laminas-mvc
<?php
declare(strict_types=1);
namespace Application\Controller;
use App\Forms\Csrf\CsrfGuardInterface;
use Laminas\Form\FormElementManager;
use Psr\Container\ContainerInterface;
/** @api */
final class AvatarControllerFactory
{
public function __invoke(ContainerInterface $container): AvatarController
{
return new AvatarController(
$container->get(FormElementManager::class),
$container->get(CsrfGuardInterface::class),
);
}
}
Merge this file into your module configuration, as Module does in chapter 0:
<?php
declare(strict_types=1);
namespace Application;
use Laminas\Router\Http\Literal;
return [
'router' => [
'routes' => [
'avatar' => [
'type' => Literal::class,
'options' => [
'route' => '/avatar',
'defaults' => ['controller' => Controller\AvatarController::class, 'action' => 'form'],
],
],
],
],
'controllers' => [
'factories' => [
Controller\AvatarController::class => Controller\AvatarControllerFactory::class,
],
],
'view_manager' => [
'template_map' => [
'forms::avatar' => __DIR__ . '/../../../vendor/laminas-howto/forms-shared/templates/avatar.phtml',
],
],
];
<?php
declare(strict_types=1);
/**
* @var Laminas\View\Renderer\PhpRenderer $this
* @var App\Forms\Avatar\AvatarForm $form
* @var string|null $status
*/
// Preparing a form with a file field sets enctype="multipart/form-data"
$form->prepare();
$this->headTitle($form->getMessages() === [] ? 'Change your photo' : 'Error: Change your photo', 'SET');
?>
<?= $this->partial('forms::error-summary', ['form' => $form]) ?>
<h1>Change your photo</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('avatar')]) ?>
<?= $this->formElement($form->get('upload')) ?>
<?= $this->form()->closeTag() ?>
<?php
declare(strict_types=1);
namespace App\Handler;
use App\Csrf\MezzioCsrfGuard;
use App\Forms\Avatar\AvatarForm;
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\Message\UploadedFileInterface;
use Psr\Http\Server\RequestHandlerInterface;
/** @api */
final readonly class AvatarHandler implements RequestHandlerInterface
{
public function __construct(
private FormElementManager $forms,
private TemplateRendererInterface $renderer,
) {}
#[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(AvatarForm::class);
$form->setCsrfGuard(new MezzioCsrfGuard($guard));
if ($request->getMethod() === 'POST') {
/** @var array<string, mixed> $fields */
$fields = $request->getParsedBody() ?? [];
if ($form->setSubmission($fields, $request->getUploadedFiles()) && $form->isValid()) {
/** @var array{avatar: UploadedFileInterface} $data */
$data = $form->getData();
// Store $data['avatar'] here, under a name you choose, outside the public directory
$flash->flash('status', "Received your new photo: {$data['avatar']->getSize()} bytes.");
return new RedirectResponse('/avatar', 303);
}
}
return new HtmlResponse($this->renderer->render('forms::avatar', [
'form' => $form,
'status' => $flash->getFlash('status'),
]));
}
}
<?php
declare(strict_types=1);
namespace Application\Controller;
use App\Forms\Avatar\AvatarForm;
use App\Forms\Csrf\CsrfGuardInterface;
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 AvatarController extends AbstractActionController
{
public function __construct(
private readonly FormElementManager $forms,
private readonly CsrfGuardInterface $guard,
) {}
public function formAction(): Response|ViewModel
{
$form = $this->forms->get(AvatarForm::class);
$form->setCsrfGuard($this->guard);
/** @var Request $request */
$request = $this->getRequest();
/** @var FlashMessenger $flash */
$flash = $this->plugin('flashMessenger');
if ($request->isPost()) {
/** @var Parameters $fields */
$fields = $request->getPost();
/** @var Parameters $files */
$files = $request->getFiles();
if ($form->setSubmission($fields->toArray(), $files->toArray()) && $form->isValid()) {
/** @var array{avatar: array{tmp_name: string, size: int}} $data */
$data = $form->getData();
// Store $data['avatar'] here, under a name you choose, outside the public directory
$flash->addSuccessMessage("Received your new photo: {$data['avatar']['size']} bytes.");
return $this->redirect()->toRoute('avatar')->setStatusCode(303);
}
}
$view = new ViewModel([
'form' => $form,
'status' => $flash->getSuccessMessages()[0] ?? null,
]);
return $view->setTemplate('forms::avatar');
}
}
How it works
A file has its own kind of input. FileInput runs its validators before its filters, the other way round from other inputs, so a file is checked before anything moves it.
Take the file from the uploads. Mezzio and laminas-mvc keep posted fields and uploaded files apart. setSubmission() joins them, replacing whatever was posted as avatar, so text in the request can never stand in for a file.
The value differs. Mezzio gives you a PSR-7 UploadedFileInterface. laminas-mvc gives you the array PHP builds in $_FILES. The form and its rules are the same.
Name the upload check yourself. FileInput adds UploadFile when you leave it out, with messages that mention php.ini. Listing it first lets you say what to do instead.
Read the contents. The file name and the type sent by the browser can say anything. MimeType looks inside the file. Give it the exact types you accept: IsImage also allows formats such as SVG, which can carry scripts.
Stop at the first failure. break_chain_on_failure means a text file is not also reported as having the wrong size.
The page helps before anything is sent. The hint states the rules and is tied to the field with aria-describedby. accept narrows what the file chooser offers. Neither replaces the validators.
multipart/form-data comes from prepare(). Without it the browser sends only the file's name. Call prepare() before opening the form.
A file field cannot be refilled. After any error the person has to choose the file again.
File size limits
Three limits apply, and the smallest one wins.
| Limit | Set in | When a file is over it |
|---|---|---|
| 1MB | The Size validator |
The form says so |
upload_max_filesize, 2MB by default |
php.ini |
PHP discards the file and records an error, which UploadFile reports |
post_max_size, 8MB by default |
php.ini |
PHP discards everything, including the CSRF token |
Without help, the last case looks like an expired form. setSubmission() returns false when nothing at all arrived, and puts the size message on the field.
PHP also raises a startup warning for that request. With display_errors and display_startup_errors both on, the warning is printed before the response, and Mezzio fails with "Output has been emitted previously". Keep them off in production. The example applications turn it off when they start.
Your web server may have its own limit, such as client_max_body_size in nginx. A request over that never reaches PHP.
Before you use this for real
- Where the "Store" comment is, save the file under a name you generate, outside the public directory.
- Never use the name sent by the browser as a path.
- Re-encode the image, for example with GD or Imagick. That drops location data and anything hidden after the picture.
- Serve stored files with the correct
Content-TypeandX-Content-Type-Options: nosniff. - Check that the person is signed in, and change only their own photo.
- Limit how often one person can upload.
Further opportunities
None of these are built or tested here. Add the ones your site needs.
| Opportunity | Where | How |
|---|---|---|
| Move the file while filtering | Input filter | Add the RenameUpload filter. With PSR-7 uploads it also needs a stream factory and an uploaded file factory |
| Keep a good file while other fields have errors | Form and storage | Put it in temporary storage, and carry a reference you can verify |
| Show the current photo | Template | Add an image with suitable alternative text above the field |
| Preview and crop | A small script | Keep the plain file field working without it |
| Accept several files | Form | Add the multiple attribute. The value becomes a list, and the code that stores it must expect one |
| Scan for malware | Handler | Scan before you store the file |
| Upload large files | Storage service | Send them straight to object storage with a signed address |
Common mistakes
- Trusting the file name, extension or browser supplied type.
- Using
IsImagefor pictures you will show to other people. - Forgetting
prepare(), so the form is not multipart. - Allowing more in
Sizethanupload_max_filesizepermits. - Assuming a POST request always has fields.
- Storing uploads where the web server will run them.