edt*_*edt 17 php email content-type file-get-contents
我正在使用PHP发送带附件的电子邮件.附件可以是几种不同文件类型中的任何一种(pdf,txt,doc,swf等).
首先,脚本使用"file_get_contents"获取文件.
之后,脚本在标题中回响:
Content-Type: <?php echo $the_content_type; ?>; name="<?php echo $the_file_name; ?>"
Run Code Online (Sandbox Code Playgroud)
如何为$ the_content_type设置正确的值?
dec*_*eze 27
我正在使用此功能,其中包括几个回退以补偿旧版本的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;
}
Run Code Online (Sandbox Code Playgroud)
它尝试使用较新的PHP finfo函数.如果这些不可用,它将使用mime_content_type替代方法,并包含Upgrade.php库中的替代品以确保存在.如果那些没有返回任何有用的东西,它将尝试操作系统的file命令.只有在*NIX系统上可用的AFAIK,如果您计划在Windows上使用它,您可能想要更改或删除它.如果没有任何效果,它exif_imagetype只会尝试作为图像的后备.
我注意到不同的服务器在支持mime类型功能方面差异很大,并且Upgrade.php的mime_content_type替换远非完美.有限的exif_imagetype功能,无论是原始版本还是Upgrade.php替代版,都可以非常可靠地运行.如果你只关心图像,你可能只想使用最后一个.
它很容易在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.
?>
Run Code Online (Sandbox Code Playgroud)
函数mime_content_type()的PHP文档 希望它可以帮助某人