How to get MIME Type of a file to be downloaded?
Using the finfo_file function from the FileInfo extension (enabled by default in PHP 5.3). http://www.php.net/manual/en/function.finfo-file.php
From the example in the documentation
$finfo = finfo_open(FILEINFO_MIME_TYPE);
echo finfo_file($finfo, $filename);
finfo_close($finfo);
In PHP versions prior to 5.3 the pecl extension can be installed http://pecl.php.net/package/Fileinfo
However in this case it requires the magic_open (libmagic) library http://sourceforge.net/projects/libmagic
The alternative is to use the deprecated function mime_content_type($filename)
http://au.php.net/manual/en/function.mime-content-type.php
Which relies on the mime.magic file
OM The Eternity
M a PHP Programmer.. And an Experienced Tester, And a Vocalist...
Updated on June 04, 2022Comments
-
OM The Eternity almost 2 years
I Have to download the listed file on click of the link, for whic I have used the below scripot, but I when the file gets dowloaded, it cannot idenetify the extension of downloaded file. So, How to get MIME Type of a file to be downloaded? _Please Help...
$filename = $_GET['val']; // Fetch the file info. $filePath = $_SERVER['DOCUMENT_ROOT'] . "dfms/images/uploads/".$filename; if(file_exists($filePath)) { echo $fileName = basename($filePath); $fileSize = filesize($filePath); // Output headers. header("Cache-Control: private"); header("Content-Type: application/octet"); header("Content-Length: ".$fileSize); header("Content-Disposition: attachment; filename=".$fileName); // Output file. readfile ($filePath); exit(); } else { die('The provided file path is not valid.'); }
-
OM The Eternity over 13 yearsIts not working!!!it give me... Warning: finfo_open() expects parameter 1 to be long, string given in C:\wamp\www\dfms\support-scripts\download.php on line 24 Warning: finfo_file(): supplied argument is not a valid file_info resource in C:\wamp\www\dfms\support-scripts\download.php on line 25
-
Jessedc over 13 yearsI think Jacob may have mistyped his example. The first line should read
$finfo = finfo_open(FILEINFO_MIME);
that's just reading the documentation over at: php.net/manual/en/function.finfo-open.php -
Jacob over 13 yearsFILEINFO_MIME_TYPE has been available since 5.3, FILEINFO_MIME is as defined by RFC 2045 so the former should be used if available.
-
Jessedc over 13 yearsOM The Eternity may not be running PHP 5.3 in that case :p
-
Joe Horn over 3 yearsmime_content_type() is not deprecated function.