PHP+图像类型检测


PHP+Image type detection

我有一个电子邮件脚本,通过附件从服务器发送文件。电子邮件是使用phpmailer发送的,附加文件的代码如下所示:

$_img = (object) ($img);
if (!empty($_img->src)) {
    $ext = substr($_img->src, -3); 
    $imginfo_array = getimagesize($_img->src);
    $mime_type = $imginfo_array['mime'];                    
    switch($mime_type) {
        case "image/jpeg":
            $type = "image/jpeg";
            break;
        case "image/png":
            $type = "image/png";
            break;
        case "image/gif":
            $type = "image/gif";
            break;                                  
    }
    $string = file_get_contents($_img->src); 
    $mail->AddStringAttachment($string, $i . '.' . $ext, 'base64', $type);
}

在将图像添加到服务器之前未正确保存该问题。如果一个用户决定文件"test.jpg"应该是"test.png",附加的文件将不会通过电子邮件可见。

$_img->src是保存在服务器上的文件。

我正在尝试检查mime类型,但仍然没有成功。我希望能够告诉脚本,正确的文件类型是一个自动检测不确定的扩展。谁能给我点提示,告诉我该怎么做?

        $_img = (object) ($img);
        if (!empty($_img->src)) {
            //$ext = substr($_img->src, -3);
            // better solution for get file extension (with variable length: "jpeg" or "jpeg")
            $ext = pathinfo($_img->src, PATHINFO_EXTENSION); 
            $imginfo_array = getimagesize($_img->src);
            $mime_type = $imginfo_array['mime'];                    
            switch($mime_type) {
                case "image/jpeg":
                    $type = "image/jpeg";
                    $ext = 'jpg';
                    break;
                case "image/png":
                  $type = "image/png";
                  $ext = 'png';
                  break;
               case "image/gif":
                  $type = "image/gif";
                  $ext = 'gif';
                  break;
               // fix for others mime type        
               default:    
                  $type = "application/octet-stream";
            }               
            // for binary file use AddAttachment()
            //$string = file_get_contents($_img->src);                 
            //$mail->AddStringAttachment($string, $i . '.' . $ext, 'base64', $type);
            // I hope that the variable $i is set from previous code              
            $mail->AddAttachment($_img->src, $i . '.' . $ext, 'base64', $type)
        }

您可以使用返回的imginfo_array的索引2处的IMAGETYPE_XXX常量来检测图像的类型。您使用的返回mime字段不太可靠。

看到文档:http://php.net/manual/en/function.getimagesize.php

类型作:http://php.net/manual/en/image.constants.php