简体   繁体   English

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

[英]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.据我了解, - 图像(jpeg、gif 等)可能包含有效的 php/python/perl 等代码。 So - anyone can create file that will be valid jpeg at the same time can be executed by PHP interpreter.所以 - 任何人都可以创建有效的 jpeg 文件,同时可以由 PHP 解释器执行。 (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?用 GD 或 imagemagic 重新编码图像会起作用吗?

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).您的解释器(Perl、PHP 等)应设置为仅执行某些文件类型(即 .php 或 .php5)。 There's no reason Perl or PHP should be parsing image files.没有理由 Perl 或 PHP 应该解析图像文件。

Just use the following common sense to protect yourself:只需使用以下常识来保护自己:

1) Verify the mime type of the document 1)验证文档的mime类型
2) Enforce policies that only allow uploading files of a certain extension 2) 执行只允许上传特定扩展名文件的政策
3) Don't accept filenames at face value. 3) 不要接受表面价值的文件名。 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. 4)如果你真的很偏执,找一些代码来检查字节签名对于给定的文件类型上传是否有效。

You should configure your webserver not to allow your image filename extensions to get interpreted by PHP.你应该配置你的网络服务器不允许你的图像文件扩展名被 PHP 解释。 As showed on the page linked in the question, images can contain PHP code.如问题中链接的页面所示,图像可以包含 PHP 代码。 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.";  
}  
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM