Php 强制下载脚本和readfile:为什么readfile输出我的html页面?
我正在尝试为webroot以外的用户发送文件(附件)。我制作了forcedownload脚本,它在头文件中发送文件并在流中输出。这很好,直到我调用readfile(也可以是header设置),它输出一个包含一半html源代码(这个特定页面)的文件。我创建了file_get_contents(),该文件包含正确的字符串:“test”。这里有什么问题Php 强制下载脚本和readfile:为什么readfile输出我的html页面?,php,stream,readfile,output,Php,Stream,Readfile,Output,我正在尝试为webroot以外的用户发送文件(附件)。我制作了forcedownload脚本,它在头文件中发送文件并在流中输出。这很好,直到我调用readfile(也可以是header设置),它输出一个包含一半html源代码(这个特定页面)的文件。我创建了file_get_contents(),该文件包含正确的字符串:“test”。这里有什么问题 <?php //The path where the files are stored $file_path = ""; if(isset
<?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;
?>
$文件名为test.txt,包含字符串“test”。Mime/内容类型正确
但是,此脚本的输出是html源代码。从文档中,他们在读取文件
之前进行了两次调用(强制下载):ob_clean()
和flush()
。我的假设是,他们调用这些来确保发送了标题,并且客户机理解即将出现的内容
我建议在那里添加这些,它应该会起作用。文档调用一个
ob_clean();冲洗()代码>(我假设已发送头)。你试过了吗?@Marc B,包含download.php的页面的html源代码。在调用此下载内容之前,你确定正在进行任何输出吗?输出完成后,不能发出header()
调用performed@Brad克里斯蒂,不,我忘了,谢谢,那把它修好了。如果你回答这个问题,我可以给你学分。马克B,也谢谢你的帮助。