我正在使用PHP发送带有附件的电子邮件。附件可以是几种不同的文件类型(pdf,txt,doc,swf等)中的任何一种。首先,脚本使用“ file_get_contents”获取文件。后来,脚本在标头中回显:Content-Type: <?php echo $the_content_type; ?>; name="<?php echo $the_file_name; ?>"如何为$ the_content_type设置正确的值?
3 回答
![?](http://img1.sycdn.imooc.com/5333a1660001394602000200-100-100.jpg)
阿波罗的战车
TA贡献1862条经验 获得超6个赞
我正在使用此函数,其中包括几个后备功能,以补偿旧版本的PHP或简单的不良结果:
function getFileMimeType($file) { if (function_exists('finfo_file')) { $finfo = finfo_open(FILEINFO_MIME_TYPE); $type = finfo_file($finfo, $file); finfo_close($finfo); } else { require_once 'upgradephp/ext/mime.php'; $type = mime_content_type($file); } if (!$type || in_array($type, array('application/octet-stream', 'text/plain'))) { $secondOpinion = exec('file -b --mime-type ' . escapeshellarg($file), $foo, $returnCode); if ($returnCode === 0 && $secondOpinion) { $type = $secondOpinion; } } if (!$type || in_array($type, array('application/octet-stream', 'text/plain'))) { require_once 'upgradephp/ext/mime.php'; $exifImageType = exif_imagetype($file); if ($exifImageType !== false) { $type = image_type_to_mime_type($exifImageType); } } return $type;}
它尝试使用较新的PHP finfo
函数。如果这些选项不可用,它将使用mime_content_type
替代方法,并包括Upgrade.php库中的直接替换项,以确保存在该替换项。如果这些命令没有返回任何有用的信息,它将尝试使用OS的file
命令。仅在* NIX系统上可用的AFAIK,如果打算在Windows上使用它,则可能需要更改或取消该设置。如果没有任何效果,它将exif_imagetype
仅作为图像的后备。
我已经注意到,不同的服务器在支持mime类型的功能方面差异很大,而且Upgrade.php的mime_content_type
替代还远远不够完美。有限的exif_imagetype
功能,无论是原始功能还是Upgrade.php替换功能,都可以正常运行。如果您只关心图像,则可能只想使用最后一个。
![?](http://img1.sycdn.imooc.com/54584d9f0001043b02200220-100-100.jpg)
catspeake
TA贡献1111条经验 获得超0个赞
在php中拥有它非常容易。
只需调用以下php函数 mime_content_type
<?php $filelink= 'uploads/some_file.pdf'; $the_content_type = ""; // check if the file exist before if(is_file($file_link)) { $the_content_type = mime_content_type($file_link); } // You can now use it here.?>
函数mime_content_type()的PHP文档 希望对您有所帮助
![?](http://img1.sycdn.imooc.com/533e50ed0001cc5b02000200-100-100.jpg)
慕尼黑的夜晚无繁华
TA贡献1864条经验 获得超6个赞
这是一个使用finfo_open的示例,该示例在PHP5和PECL中可用:
$mimepath='/usr/share/magic'; // may differ depending on your machine// try /usr/share/file/magic if it doesn't work$mime = finfo_open(FILEINFO_MIME,$mimepath);if ($mime===FALSE) { throw new Exception('Unable to open finfo');}$filetype = finfo_file($mime,$tmpFileName);finfo_close($mime);if ($filetype===FALSE) { throw new Exception('Unable to recognise filetype');}
另外,您可以使用已弃用的 mime_ content_类型函数:
$filetype=mime_content_type($tmpFileName);
或使用操作系统的内置功能:
ob_start();system('/usr/bin/file -i -b ' . realpath($tmpFileName));$type = ob_get_clean();$parts = explode(';', $type);$filetype=trim($parts[0]);
- 3 回答
- 0 关注
- 1310 浏览
添加回答
举报
0/150
提交
取消