0

Is there any already implemented way to validate file extension in Symfony? File and Image validators can only validate mime type. Is there any way to do it or do I have to use a custom validator / callback?

user2394156
  • 1,792
  • 4
  • 16
  • 33

1 Answers1

2

You could use a RegexValidator if all you want to validate about is the file extension. Do keep in mind that a file extension in no way guarantees the contents of the file. Someone could upload an executable as a .png for instance.

Example

new RegexValidator('/(.+)(\.jpg|\.png|\.gif)$/')

Will match any filename ending in .jpg, .png or .gif

If you want more control over it (for example, passing an array of allowed extensions) I would recommend using a CallbackValidator or making your own. Good luck!

  • You're right about the contents of the file. However if I validate only the MIME type then someone could upload, for example, a valid php file with '.php' extension that contains valid png content with php code in its comments. That's why both MIME type and file extension should be validated. It's kind of sad that Sf developers haven't provided a native way to do this – user2394156 Aug 07 '17 at 09:53
  • Very true, but neither method really protects against valid png content with PHP code. The easiest way to not have uploaded files exploit PHP is to not have PHP touch the uploaded files after uploading, but to serve them statically from a web server I suppose. – Jelle Kapitein Aug 07 '17 at 10:13