我必须在单击链接时下载列出的文件,为此我使用了下面的脚本,但是当我下载文件时,它无法识别下载文件的扩展名。那么,如何获取要下载的文件的MIME类型呢? _请帮助...
$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.');
}
最佳答案
使用 FileInfo 扩展中的 finfo_file 函数(在 PHP 5.3 中默认启用)。 http://www.php.net/manual/en/function.finfo-file.php
来自文档中的例子
$finfo = finfo_open(FILEINFO_MIME_TYPE);
echo finfo_file($finfo, $filename);
finfo_close($finfo);
在 5.3 之前的 PHP 版本中,可以安装 pecl 扩展 http://pecl.php.net/package/Fileinfo
但是在这种情况下,它需要 magic_open (libmagic) 库 http://sourceforge.net/projects/libmagic
替代方法是使用已弃用的函数 mime_content_type($filename)
http://au.php.net/manual/en/function.mime-content-type.php
它依赖于 mime.magic 文件
关于php - 如何获取要下载的文件的 MIME 类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4966045/