Downloading PHP images. How can I protect against images containing code?

From what I understand, images (jpeg, gif, etc.) may contain valid php / python / perl code, etc. That way, anyone can create a file that will be a valid jpeg, at the same time it can be executed using a PHP interpreter. (here is the description: link )

So - I was wondering - is there a way to remove malicious code from images? will recode images using gd or imagemagic work?

Thanks!

+7
source share
2 answers

Actual images will not contain code. But nothing prevents someone from trying to download the downloaded "image" file, and then trying to get it to execute.

Your interpreters (Perl, PHP, independently) should be configured so that they only execute certain types of files (i.e...php or .php5). There is no reason Perl or PHP should process image files.

Just use the following common sense to protect yourself:

1) Check the mime type of the document
2) Forced policies that allow you to upload files of a specific extension
3) Do not accept file names at face value. Create your own internal file name and use the database table to maintain the mapping.
4) If you are really paranoid, find the code to verify that byte signatures are valid for a given file type download.

+4
source

You must configure your web server to not allow the extension of image file names in order to interpret their PHP. As shown on the page related to the question, images may contain PHP code. Always check the file name extension for whitelist:

<?php $whitelist = '/\.(?:jpe?g|png|gif)$/i'; if (!preg_match($whitelist, $_FILES['userfile']['name'])) { echo "Bad filename extension."; exit; } $uploaddir = 'uploads/'; $uploadfile = $uploaddir . basename($_FILES['userfile']['name']); if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) { echo "File is valid, and was successfully uploaded."; } else { echo "File uploading failed."; } ?> 
0
source

All Articles