2 minute read
May 21, 2018

How to control the type of files that can be uploaded in Statamic via the assets fieldtype

One of the most basic security best practices, when it comes to keeping a website secure, is restricting the type of files that can be uploaded.

Out of the box, Statamic doesn't provide any limitations on the type of files that can be uploaded to an assets fieldtype, unless you explicitly configure it to have so. This isn't really ideal, as you don't want people being able to upload things like JavaScript files to your website, which could then – in theory – be linked to and run.

Luckily, Statamic can make use of Laravel's validation rules.

It's not all about security

Let's say you have an assets fieldtype. Because of the part of the website the image will be placed, you don't want people being able to upload a jpg or jpeg which will have a background. Because of that, you only want them to be able to upload image types that support transparency - i.e. png and gif (let's ignore svg for the time being).

Out of the box, your fieldset might look something like this:


image:
  type: assets
  display: Image
  instructions: Please use only PNGs and GIFs
  container: main

Now while you'd hope people would read your instructions, as developers we all know that doesn't happen. So how do you stop people from uploading other file types (e.g. jpg, jpeg, docx) etc?

Simply add an extra rule into your field called validate. You can define the extensions that are allowed by adding "ext:png, gif" and so on to your validation rules.


image:
  type: assets
  display: Image
  instructions: Please use only PNGs and GIFs
  container: main
  validate: "ext:png, gif"

Now when someone tries to upload a type of file that isn't allowed, Statamic will stop users from doing so.


Resources:

Statamic Docs
Assets Fieldtype

Laravel Docs
Laravel 5.1 Validation