1

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()?

Nadine
  • 777
  • 1
  • 11
  • 24
  • You should first check if the filetype is an image, and save it with an image extension. How do people upload `$image`? – Antony Jan 31 '17 at 19:39
  • Thanks. They will upload it through the plugin (slimimagecropper.com) which looks at the $_FILES array to get the image. As far as I can see, this plugin doesn't do any XSS checks server side, hence why I want to modify the plugin code where it writes `file_put_contents()` – Nadine Jan 31 '17 at 19:42

2 Answers2

2

There's a few things you can do to sanitise the user upload. Everything in $_FILES can be manipulated, so don't trust it at all.

Filename:

Never trust the filename given to you by the user - always save it as a different and sanitised input. image.jpg.php -> uniquestring_programatically_generated.jpg.

Getimagesize:

Use the method getimagesize($filename) to verify it's an actual image, and it has a size.

Farkie
  • 3,307
  • 2
  • 22
  • 33
1

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
    }
}
Community
  • 1
  • 1
Antony
  • 1,253
  • 11
  • 19