Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 62 ยท Forms and Validation

File Uploads

Handle file uploads in Symfony safely: FileType, UploadedFile, the File constraint, safe file names, moving files and Flysystem storage, with runnable stand-ins.

Letting users upload files is one of the riskiest features a web application can have. A file arrives with a name the user chose, a content type the user's browser guessed and bytes the user controls. If you trust any of those three, you can end up serving a script as an image, overwriting another user's file or filling your disk. Symfony gives you the pieces to do it right: a FileType form field, an UploadedFile object, a File validation constraint and a clean way to move the result somewhere permanent.

This lesson follows one upload from browser to storage and points out where each safeguard belongs. The real framework code is read-only here (the site cannot run Symfony or accept uploads), and two stand-ins show the logic that matters: checking a file by its real content, and building a safe, collision-free name.

What happens to an upload

When a form with enctype="multipart/form-data" is submitted, PHP stores each file in a temporary directory before your code runs. Symfony's Request wraps it in an UploadedFile, available in $request->files. PHP deletes the temporary file at the end of the request, so you must move it if you want to keep it.

flowchart LR
    B["Browser<br/>multipart/form-data"] --> P["PHP stores a<br/>temporary file"]
    P --> R["Request->files<br/>(UploadedFile)"]
    R --> V["Validate<br/>size, real type"]
    V -->|"valid"| S["Move to storage<br/>(safe new name)"]
    V -->|"invalid"| E["Form error"]

PHP holds the file temporarily; your code validates it and moves it before the request ends.

Two PHP settings limit uploads before Symfony sees anything: upload_max_filesize (per file) and post_max_size (whole request). If a file exceeds them, the form arrives with the file missing or flagged with an error, so keep these settings at least as large as your constraint allows.

The form field

A file field is declared with FileType. Because the field holds a transient upload rather than a value you store in a column, it is usually unmapped and validated with the File constraint:

PHP
<?php

namespace App\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Validator\Constraints\File;
use Symfony\Component\Validator\Constraints\NotNull;

class DocumentType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder
            ->add('title', TextType::class)
            ->add('attachment', FileType::class, [
                'label' => 'PDF file',
                'mapped' => false,
                'constraints' => [
                    new NotNull(message: 'Please choose a file.'),
                    new File(
                        maxSize: '2M',
                        mimeTypes: ['application/pdf'],
                        mimeTypesMessage: 'Please upload a valid PDF document.',
                    ),
                ],
            ]);
    }
}

In Twig, a form with a file field needs no special attribute when you render it with form_start(form): Symfony adds enctype="multipart/form-data" automatically when the form contains a FileType. For several files use 'multiple' => true and wrap the constraint in All. The form basics are in Forms: Building and Rendering, and the type options in Form Types and Options.

The File constraint

File is where safety lives. Its most useful options are maxSize (plain bytes or '500k', '2M'), mimeTypes, extensions and the matching message options. The important point is how the type is detected: Symfony inspects the file's content through PHP's file-info support, not the extension and not the Content-Type header the browser sent. A file named photo.png that actually contains a PHP script is rejected by mimeTypes: ['image/png'].

There are also specialised constraints: Image adds checks for width, height, aspect ratio and a real image decode, which is the one to use for avatars, and All applies another constraint to each element of a multi-upload.

Moving the file

Once the form is valid, read the UploadedFile from the field, build a new name and move it:

PHP
<?php

use Symfony\Component\HttpFoundation\File\Exception\FileException;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\String\Slugger\SluggerInterface;

public function upload(Request $request, SluggerInterface $slugger): Response
{
    $form = $this->createForm(DocumentType::class);
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
        /** @var UploadedFile $file */
        $file = $form->get('attachment')->getData();

        $original = pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME);
        $safe = $slugger->slug($original);
        $newName = $safe.'-'.uniqid().'.'.$file->guessExtension();

        try {
            $file->move($this->getParameter('documents_directory'), $newName);
        } catch (FileException $e) {
            $this->addFlash('error', 'The file could not be saved.');
            return $this->redirectToRoute('document_new');
        }

        // store $newName on your entity, never the original name as a path
        return $this->redirectToRoute('document_list');
    }

    return $this->render('document/new.html.twig', ['form' => $form]);
}

Every line here guards against something. getClientOriginalName() is user input: slugging it removes slashes, dots and unusual characters, which prevents path traversal such as ../../index.php. The unique suffix prevents two users uploading cv.pdf from overwriting each other. guessExtension() derives the extension from the detected content type instead of trusting the client's extension, and getClientMimeType() should never be used for decisions because the browser (or an attacker) chose it. Finally, documents_directory is a parameter defined in config/services.yaml, so the path lives in one place. Two more rules: keep uploaded files outside public/ unless they are meant to be fetched directly, and serve private ones through a controller that checks permission and returns a BinaryFileResponse (see Responses, JSON and Redirects).

Since Symfony 7.1, a controller can also receive an upload directly with the #[MapUploadedFile] argument attribute, passing constraints to it, which is convenient for endpoints that take a single file.

Storage with Flysystem

move() writes to the local disk of one server. If you run several servers, or want to switch to S3 or another cloud later, wrap storage in an abstraction. The popular choice is Flysystem, installed with composer require league/flysystem-bundle. You configure named storages:

YAML
# config/packages/flysystem.yaml
flysystem:
    storages:
        documents.storage:
            adapter: 'local'
            options:
                directory: '%kernel.project_dir%/var/storage/documents'

Symfony then lets you autowire a FilesystemOperator by argument name ($documentsStorage for the storage called documents.storage), and your code never knows whether the bytes land on a disk or in a bucket:

PHP
public function __construct(private FilesystemOperator $documentsStorage) {}

public function store(UploadedFile $file, string $name): void
{
    $stream = fopen($file->getPathname(), 'r');
    $this->documentsStorage->writeStream($name, $stream);
    if (is_resource($stream)) {
        fclose($stream);
    }
}

Moving from local disk to S3 then means changing the adapter configuration, not the application code. This is the same idea as program-to-an-interface, and it also makes tests trivial because a test can use an in-memory adapter.

Two stand-ins

The first stand-in validates a fake upload like the File constraint does: it parses sizes such as 2M, ignores the claimed type and sniffs the content's first bytes ("magic numbers"). Run it and note that the disguised file is caught.

PHP Checking an upload by its real content (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The second stand-in builds a safe stored name (slug, content-based suffix, extension from detected type) and writes through a storage interface with an in-memory adapter, the same shape as FilesystemOperator.

PHP Safe names and a storage interface (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The attacker's ../../public/index.php ends up as an ordinary slug, and two uploads of the same client name do not collide.

Production checklist

  • Validate size and detected type; never trust the client name or MIME header.
  • Store a generated name; keep the original name only as display data (escaped).
  • Keep uploads outside the web root, or serve them from a separate domain or bucket.
  • Never execute uploaded files, and never allow server-side script extensions to land in a publicly served directory.
  • Limit the request size at the web server (client_max_body_size in nginx) as well as in PHP.
  • Consider virus scanning for user-to-user sharing, and image re-encoding for avatars (stripping metadata and any embedded payload).
  • For large or numerous files, upload straight to object storage with a signed URL instead of passing bytes through PHP.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is the mimeTypes option of the File constraint safer than checking the file extension?

    The constraint inspects the actual bytes. Extensions and browser-supplied headers are chosen by the client and can be faked.
  2. 2. What should you store on disk as the file name?

    A generated name prevents path traversal and collisions. The original name can be saved separately as display text.
  3. 3. What happens to the temporary file PHP created if you never move it?

    Uploaded files are temporary. Move them (or write them to storage) before the request finishes.
  4. 4. What is the main benefit of Flysystem for storing uploads?

    Flysystem is a storage abstraction. Adapters differ, your application code stays the same, and tests can use an in-memory adapter.
  5. 5. Why does an upload field usually have 'mapped' => false?

    The data is a transient upload. You read it from the form, move it and then store the resulting name on your entity yourself.

Summary

  • PHP keeps an upload in a temporary file; Symfony wraps it in UploadedFile, and you must move it before the request ends.
  • Use FileType (usually unmapped) with the File or Image constraint; type detection uses the file content.
  • Build a new name from a slug and a unique part, take the extension from guessExtension(), and never trust client names or MIME headers.
  • Keep uploads outside public/ unless they are meant to be public; serve private files through a controller.
  • Flysystem puts local disk, S3 and other storages behind one interface.

Next up: Doctrine ORM Setup.