我正在尝试为 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”。哑剧/内容类型是正确的。
然而,这个脚本的输出是 html 源代码。