首页 >后端开发 >php教程 >PHP 中如何判断文件的内容类型?

PHP 中如何判断文件的内容类型?

Susan Sarandon
Susan Sarandon原创
2024-11-14 12:19:02715浏览

How to Determine the Content Type of a File in PHP?

如何在 PHP 中确定文件内容类型

发送带有附件的电子邮件时,为附件设置正确的 Content-Type 标头至关重要附件以确保成功交付和正确展示。在 PHP 中,您可以使用 file_get_contents() 函数来检索附件的内容,但确定内容类型需要额外的步骤。

getFileMimeType() 函数

为了简化此任务,请考虑使用以下 getFileMimeType()函数:

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;
}

工作原理

此函数尝试多种方法来确定内容类型:

  1. finfo_file ():如果可用,它使用 PHP finfo
  2. mime_content_type():如果 finfo 不可用,则回退到 mime_content_type() 替代方案。
  3. file 命令:如果上述方法失败,它尝试执行操作系统的 mime 类型的文件命令
  4. exif_imagetype():作为最后的手段,它使用 exif_imagetype() 来确定图像的 mime 类型。

通过使用以下组合通过这些方法,该函数提供了一种强大的方法来检索各种文件类型的内容类型。

以上是PHP 中如何判断文件的内容类型?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn