Home >Backend Development >PHP Tutorial >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; }
How it Works
This function tries several methods to determine the content type:
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!