我正在尝试为webroot之外的用户发送文件(附件)。我制作了强制下载脚本,它在标题中发送文件并以流形式输出。这很好用,直到我调用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源。
答案 0 :(得分:4)
在readfile
文档中,他们在readfile
(强制下载)前拨打两个电话:ob_clean()
&amp; flush()
。我的假设是他们称之为确保标题已发送,客户理解其内容即将发布。
我建议在那里添加它们,它应该有用。