How to Reliably Determine File Content-Type in PHP?

Linda Hamilton
Release: 2024-11-15 05:26:02
Original
543 people have browsed it

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;
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template