Php 检查安全图像上载
我想从浏览器窗口将图像上载到服务器。 我正在使用此功能上载图像。图像由GD库上载。Php 检查安全图像上载,php,security,upload,image-upload,Php,Security,Upload,Image Upload,我想从浏览器窗口将图像上载到服务器。 我正在使用此功能上载图像。图像由GD库上载。 您对该代码有何看法? 我想知道是否还有办法上传恶意文件 <?php function imageUpload($name, $thumb = false, $max_size = 5242880, $height = null, $width = null, $T__height = 100, $T__width = 100) { if(!isset($_FILES[$name])) {
您对该代码有何看法?
我想知道是否还有办法上传恶意文件
<?php
function imageUpload($name, $thumb = false, $max_size = 5242880, $height = null, $width = null, $T__height = 100, $T__width = 100)
{
if(!isset($_FILES[$name]))
{
return false;
}
$allowedTypes = array('image/gif', 'image/jpeg', 'image/png', 'image/wbmp');
$image = &$_FILES[$name];
if ($image['error'] == 0 && in_array($image['type'], $allowedTypes) && $image['size'] <= $max_size)
{
$in = '';
switch ($image['type'])
{
case 'image/gif':
$in = 'imagecreatefromgif';
break;
case 'image/jpeg':
$in = 'imagecreatefromjpeg';
break;
case 'image/png':
$in = 'imagecreatefrompng';
break;
case 'image/wbmp':
$in = 'imagecreatefromwbmp';
break;
}
if ($in == '')
{
return false;
}
$src = $in($image['tmp_name']);
$height = ($height == null || $height <= 0 ? imagesy($src) : $height);
$width = ($width == null || $width <= 0 ? imagesx($src) : $width);
$dst = imagecreatetruecolor($width, $height);
imagecopyresized($dst, $src, 0, 0, 0, 0, $width, $height, imagesx($src), imagesy($src));
$fileName = '';
do
{
$fileName = makeHash(mt_rand(0, mt_getrandmax()) . microtime(true), $image['tmp_name']);
}
while(file_exists('/image/' . $fileName . '.jpg') || ($thumb && file_exists('/thumb/' . $fileName . '.jpg')));
if ($fileName == '')
{
return false;
}
imagejpeg($dst, '/image/' . $fileName . '.jpg', 75);
if ($thumb)
{
$dst = imagecreatetruecolor($T__width, $T__height);
imagecopyresized($dst, $src, 0, 0, 0, 0, $T__width, $T__height, imagesx($src), imagesy($src));
imagejpeg($dst, '/thumb/' . $fileName . '.jpg', 75);
}
imagedestroy($src);
imagedestroy($dst);
return $fileName . '.jpg';
}
}
?>
首先,任何类型的安全机制都不应依赖于mimetype,因为攻击者可以完全控制该字段(他们可以上传一个带有类型为image/gif的.php文件,该文件将通过这些检查)。然后,如果它们在文件名%00
或\00
中包含空字节,则可以绕过向映像添加.jpg扩展名的条件,例如evil.php\00.jpg
,因此当文件到达磁盘时,它将是evil.php。但是,在没有看到所有函数的情况下,很难对代码进行全面评估,因为根据它们的功能,可能会打开漏洞。(例如,不清楚文件存储在何处、调用它们的内容、加载它们等)。我投票将这个问题作为离题题来结束,因为它适合,而不是堆栈溢出。