gpt4 book ai didi

php - 如何获取要下载的文件的 MIME 类型?

转载 作者:可可西里 更新时间:2023-11-01 00:26:40 25 4
gpt4 key购买 nike

我必须在单击链接时下载列出的文件,为此我使用了下面的脚本,但是当我下载文件时,它无法识别下载文件的扩展名。那么,如何获取要下载的文件的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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com