Symfony News

New in Symfony 3.1: Strict Image Validation

Konstantin Myakshin

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.


Be trained by Symfony experts - 2016-04-05 Clichy - 2016-04-05 Clichy - 2016-04-06 Clichy


About us

What a Symfony developer should know about the framework: News, Jobs, Tweets, Events, Videos,...

Resources

Find us on Twitter

Find us on Facebook