PHP image uploads. how do I protect against images containning code?

From what I understand, - images (jpeg, gif etc.) might contain valid php/python/perl etc. code. So - anyone can create file that will be valid jpeg at the same time can be executed by PHP interpreter. (here is description: link)

So - I was wondering - is there a way to strip malicious code from images? would recoding images with GD or imagemagic work?

Thanks!


Actual images will not contain code. But there's nothing stopping someone from trying to get an "image" file uploaded, and then try and get it to execute.

Your interpreters (Perl, PHP, whatever) should be set up so that they only execute certain file types (ie .php or .php5). There's no reason Perl or PHP should be parsing image files.

Just use the following common sense to protect yourself:

1) Verify the mime type of the document
2) Enforce policies that only allow uploading files of a certain extension
3) Don't accept filenames at face value. Generate your own internal file name and use a database table to keep the mapping.
4) If you're truly paranoid, find some code to check that the byte signatures are valid for the given file type upload.


You should configure your webserver not to allow your image filename extensions to get interpreted by PHP. As showed on the page linked in the question, images can contain PHP code. Always check the filename extension against a 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.";  
}  
?>
链接地址: http://www.djcxy.com/p/52850.html

上一篇: Python获取部分函数的参数

下一篇: PHP图像上传。 如何防止包含代码的图像?