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:
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!