【发布时间】:2012-08-31 00:13:08
【问题描述】:
我正在制作一个简单的下载脚本,我的用户可以在其中下载自己的图像等。
但我遇到了一些奇怪的问题。
当我下载文件时,无论我下载什么文件类型,它都包含我的 index.php 文件中的内容。我的代码是这样的:
$fullPath = $r['snptFilepath'] . $r['snptFilename'];
if (file_exists($fullPath)) {
#echo $fullPath;
// setting headers
header('Content-Description: File Transfer');
header('Cache-Control: public'); # needed for IE
header('Content-Type: '.$r['snptFiletype'].'');
header('Content-Disposition: attachment; filename='. $filename . '.' . $r['snptExtension']);
header('Content-Length: '.$r['snptSize'].'');
readfile($fullPath)or die('error!');
} else {
die('File does not exist');
}
$r 是来自我的数据库的结果,上传文件时我在其中存储了大小、类型、路径等。
更新
当我上传和下载 *.pdf 文件时,它正在成功运行。但是当我尝试下载 *.zip 和 text/rtf、text/plain 时,它的行为很奇怪。
我的意思是奇怪:它下载完整的 index.php 文件,其中包含下载的文件内容。
回答
我从http://php.net/manual/en/function.readfile.php 复制了这个,现在可以使用了。似乎:ob_clean();成功了!谢谢大家的帮助。
#setting headers
header('Content-Description: File Transfer');
header('Content-Type: '.$type);
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
exit;
【问题讨论】:
-
你从哪里得到 $filename?
-
试试
echo $fullpath;。是空字符串吗? -
readfile("$fullPath")此处无需使用"。尝试将header和readfile替换为echo,然后查看您实际发送到用户浏览器的内容。 -
@WayneWhitty $filename 来自 url。
-
@AlexanderLarikov 当我回显标题时,它看起来很好。当回显 readfile 时,我得到了很多内容,带有“?”-sign..
标签: php