I have created a PHP class which I use to resize uploaded images.
The class checks the extension of the file and accordingly calls the proper function to start editing the image, like imagecreatefromjpeg, imagecreatefrompng, and so on…
I read that it is possible to embed malicious code in the EXIF data or other part of an image.
So how can I optimize my code and make it more secure in order to prevent that a compromised image file can run malicious code?
Is there a better way to detect the file type other that checking at its extension?
I already checked the answers given to another question (Malicious Code Through Image Upload), but it doesn’t tackle all my doubts.
A more robust code would help everyone handling uploaded images with PHP.
The workflow I am using is basically this for a JPEG file:
$uploaded_file = 'uploaded/image.jpg';
$destination_file_url = 'uploaded/image_resized.jpg';
$extension = strtolower(strrchr($uploaded_file, '.'));
.....
if (getimagesize($uploaded_file) === false) {
die("This is not an image!");
}
$newImage = imagecreatetruecolor($newWidth, $newHeight);
$image = imagecreatefromjpeg($uploaded_file);
imagecopyresampled($newImage, $image, $cropStartX, $cropStartY, 0, 0, $optimalWidth, $optimalHeight, $original_width, $original_height);
$exif = @exif_read_data($uploaded_file);
.....
imageinterlace($newImage, 1);
imagejpeg($newImage, $destination_file, 90);
imagedestroy($image);
imagedestroy($newImage);
Thanks a lot for your help!