Search code examples
phpsymfonysymfony-formssymfony-3.1

Validate file extension on Symfony3


I want to validate the file extension on Symfony3 before the file is uploaded. Until now, I am using this code (this is a simplified version just used as a snippet):

if ($form->isSubmitted() && $form->isValid()) {
    $form->handleRequest($request);
    $file = $form->get('file')->getData();
    $ext = $file->guessExtension();
    if($ext !== 'myextension' ){
        die('not allowed');
    }

    $name = md5($file->getClientOriginalName().time());
    $full_name = $name.'.'.$ext;
    $dir = __DIR__.'/../../../web/upload';
    $file->move($dir,$full_name);
}

Question is: will the file be uploaded in the temp directory anyway? is this safe? is there a better way to do it?. My biggest concern is that someone tries to upload a binary file or a script. Thanks

EDIT (thanks Gabriel Diez): the file is a property of an entity. I used assert to declare it:

   /**
     * @Assert\File(maxSize="20M")
     */
    private $file;

Solution

  • I think the better way to do it is to secure it using Symfony. As this file is part of an Entity you can use the Assert/File annotation to add some constraints and security.

    /**
     * @Assert\File(
     *     maxSize = "20M",
     *     mimeTypes = {"application/pdf", "application/x-pdf"},
     *     mimeTypesMessage = "Please upload a valid PDF"
     *     )
     */
    private $file;
    

    With this Symfony will handle this on the server side and return an error to the user if the type isn't allow. Moreover with this method you are sure users can upload only available types of file.

    You can find a list of existing mime types here and a list of all constraints of symfony available here.