首頁  >  文章  >  後端開發  >  如何在 PHP 中可靠地確定文件內容類型?

如何在 PHP 中可靠地確定文件內容類型?

Linda Hamilton
Linda Hamilton原創
2024-11-15 05:26:02545瀏覽

How to Reliably Determine File Content-Type in PHP?

Determining File Content-Type in PHP

In PHP, it's essential to determine the content-type of a file when sending it as an email attachment. This ensures the correct MIME type is specified in the header, allowing the receiving software to properly handle the file.

Obtaining the Content-Type

The recommended approach is to utilize the getFileMimeType() function:

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

This function attempts to determine the content-type using various methods, including:

  • PHP's finfo functions (if available)
    *mime_content_type() from the Upgrade.php library
  • The OS' file command (for *NIX systems)
  • exif_imagetype() for image files

By utilizing multiple methods, this function provides a reliable solution for obtaining the correct content-type, regardless of the operating system or PHP environment.

以上是如何在 PHP 中可靠地確定文件內容類型?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn