Cover of the book Symfony 5: The Fast Track

Symfony 5: The Fast Track is the best book to learn modern Symfony development, from zero to production. +300 pages showcasing Symfony with Docker, APIs, queues & async tasks, Webpack, SPAs, etc.

New in Symfony 3.1: Strict Image Validation

Warning: This post is about an unsupported Symfony version. Some of this information may be out of date. Read the most recent Symfony Docs.

Contributed by
Konstantin Myakshin in #17458.

The Image constraint is one of the most powerful constraints defined by the Validator component. It allows you to validate the max/min height and width, the max/min ratio of images, whether the format should be portrait or landscape, etc.

However, it lacked a very important check: validate that the image is not corrupted and therefore, that it will be displayed correctly in your application. That's why Symfony 3.1 includes a new detectCorrupted configuration option and its corresponding corruptedMessage:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
use Symfony\Component\Validator\Constraints as Assert;

class Product
{
    /**
     * @Assert\Image(
     *     detectCorrupted = true,
     *     corruptedMessage = "Product photo is corrupted. Upload it again."
     * )
     */
    protected $photo;
}

Internally this feature uses PHP's imagecreatefromstring() function to check that the provided contents can create a valid image. Therefore, before using this new validation, make sure that the GD extension is installed and enabled in your PHP engine.

As you can imagine, this option makes the validation be slower and consume more memory, but that's a reasonable trade-off when some images are critical for your application.

Help the Symfony project!

As with any Open-Source project, contributing code or documentation is the most common way to help, but we also have a wide range of sponsoring opportunities.

Comments

Great!

Will there be a provider using ImageMagick? I think it could be more powerful actually.
Espectacular!!
Wow, this is handy. Thanks Konstantin :) Cheers!!!

Comments are closed.

To ensure that comments stay relevant, they are closed for old posts.