gpt4 book ai didi

php - 强制下载脚本和读取文件 : Why readfile outputs my html page?

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

我正在尝试为 webroot 以外的用户发送文件(附件)。我制作了强制下载脚本,它在 header 中发送文件并在流中输出。这很好用,直到我调用 readfile(也可以是标题设置),它输出一个文件,其中包含我的 html 源代码的一半(该特定页面的)。我做了 file_get_contents() 并且文件包含正确的字符串:“test”。这里有什么问题?

<?php   
//The path where the files are stored
$file_path = "";
if(isset($_GET['file'])) {
$file_path = $_GET['file'];
}
else {
header('HTTP/1.0 404 Not Found');
die('File not found!');
}

$file_name = basename($_GET['file']);

//Make sure the file exists
if(!file_exists($file_path) && !is_file($file_name)) {
header('HTTP/1.0 404 Not Found');
die('File not found!');
}

//Initialize the actual file.
$file = $file_path;

//Notice: Remember to set fifo extension in php.ini
//Windows users must include the bundled php_fileinfo.dll DLL file in php.ini to enable this extension.
$finfo = new finfo(FILEINFO_MIME);
$mime = "";
if(function_exists("finfo_open")) {
$finfo = finfo_open(FILEINFO_MIME);
$mime = finfo_file($finfo, $file);
}
// Provide a default type in case all else fails
else {
$mime = "application/octet-stream";
}

//Set the appropriate content-type and provide the content-length.
header('Content-Description: File Transfer');
header('Content-Transfer-Encoding: binary');
header('Content-type: '.$mime);
header('Content-Disposition: attachment; filename='.$file_name);
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: '.filesize($file));

//Print the image data
readfile($file);
exit;
?>

$file 名为 test.txt 并包含字符串“test”。 Mime/content-type 是正确的。

但是这个脚本的输出是 html 源。

最佳答案

来自readfile文档,他们在 readfile 之前进行了两次调用(强制下载):ob_clean()flush()。我的假设是他们调用这些以确保 header 已发送并且客户了解有内容即将到来。

我建议在其中添加那些,它应该可以工作。

关于php - 强制下载脚本和读取文件 : Why readfile outputs my html page?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14264497/

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