Validating File Uploads

It's always a good idea to validate and sanitize user input, and never is that truer than when dealing with files. If you're writing custom code that works with files or adds them to the file manager, you definitely don't want to just import any and every file submitted to your Concrete CMS site. Here are some simple ways to validate files uploaded to your custom code.

Always Use Standard PHP Validation

It's a good idea to always validate uploaded files first with standard, non-Concrete-specific validation. If you have a web form submitting a file to the server:

<form method="post" enctype="multipart/form-data" action="<?=$view->action('save_avatar')?>">
    <input type="file" name="avatar">
    <button type="submit">Save Avatar</button>
</form>

You're going to want to make sure that your save_avatar method employs standard PHP file validation on the uploaded file:

public function save_avatar()
{
    if (isset($_FILES['avatar']) && (is_uploaded_file($_FILES['vatartmp_name']))) {
        // now you can proceed
    }
}

Validate Images

Want to make sure you're dealing with an image? Use the Image validation method in the File Validation Service

public function save_avatar()
{
    if (isset($_FILES['avatar']) && (is_uploaded_file($_FILES['avatar']['tmp_name']))) {
        $service = \Core::make("helper/validation/file");
        if ($service->image($_FILES['avatar']['tmp_name'])) {
            // The file is a valid image
        }
    }
}

Validate Extensions

It's also a good idea to validate a file's extension as well. This validation takes place against the master list of allowed Concrete file extensions, which is controllable in the Dashboard.

public function save_avatar()
{
    if (isset($_FILES['avatar']) && (is_uploaded_file($_FILES['avatar']['tmp_name']))) {
        $service = \Core::make("helper/validation/file");
        if ($service->extension($_FILES['avatar']['name'])) {
            // The file's provided extension matches a supported extension.
        }
    }
}