Search code examples
phpsecurityxssfile-put-contents

How can I validate image saved with file_put_contents()?


I am using file_put_contents($path, $image); to save an image which a user will upload through a plugin (slimimagecropper.com FYI).

I'm concerned about XSS. What is the best way to check $image for XSS before saving it with file_put_contents()?


Solution

  • Reference: PHP Validating the File Upload

    To validate if the content is an image, you should validate:

    • Its extension
      To prevent a remote file upload such as .php
    • Its mime type
      Extra check to validate its file type
    • Its content
      Preventing uploading text as image and similar

    Try using this code (Taken from the reference) to validate the extension and mime type:

    $allowedExts = array("gif", "jpeg", "jpg", "png");
    $extension = end(explode(".", $_FILES["file"]["name"]));
    if ((($_FILES["file"]["type"] == "image/gif")
    || ($_FILES["file"]["type"] == "image/jpeg")
    || ($_FILES["file"]["type"] == "image/jpg")
    || ($_FILES["file"]["type"] == "image/png"))
    && ($_FILES["file"]["size"] < 20000)
    && in_array($extension, $allowedExts))
    

    And this code to validate its content (Taken from reference as well):

    $file = $_FILES['file']['tmp_name'];
    if (file_exists($file)) {
        $imagesizedata = getimagesize($file);
        if ($imagesizedata === FALSE) {
            //not image
        } else {
            //image
        }
    }