Home >Backend Development >PHP Tutorial >How to Reliably Determine File Content-Type in PHP?

How to Reliably Determine File Content-Type in PHP?

Linda Hamilton
Linda HamiltonOriginal
2024-11-15 05:26:02617browse

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.

The above is the detailed content of How to Reliably Determine File Content-Type in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn