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()
?
Reference: PHP Validating the File Upload
To validate if the content is an image, you should validate:
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
}
}