Home > Backend Development > PHP Tutorial > How to Determine the Content Type of a File in PHP?

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

Susan Sarandon
Release: 2024-11-14 12:19:02
Original
667 people have browsed it

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

How to Determine File Content Type in PHP

When sending emails with attachments, it's crucial to set the correct Content-Type header for the attachment to ensure successful delivery and proper display. In PHP, you can use the file_get_contents() function to retrieve the attachment's contents, but determining the content type requires an additional step.

The getFileMimeType() Function

To simplify this task, consider using the following 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

How it Works

This function tries several methods to determine the content type:

  1. finfo_file(): If available, it uses the PHP finfo functions.
  2. mime_content_type(): It falls back to the mime_content_type() alternative if finfo is not available.
  3. file command: If the above methods fail, it attempts to execute the OS's file command for mime type identification.
  4. exif_imagetype(): As a last resort, it uses exif_imagetype() to determine the mime type for images.

By using a combination of these methods, the function provides a robust way to retrieve the content type of various file types.

The above is the detailed content of How to Determine the Content Type of a File 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