这是一个简单的玩具脚本,但我遇到了问题。我试图让用户使用readfile()下载一个文件,但也让脚本写入页面。在浏览器中执行此脚本后,文件被下载,但文件似乎也被打印到屏幕上。此外,我得到以下错误:
警告:无法修改标头信息-标头已由第11行/Applications/XAMPP/examplepfiles/htdocs/test.php中的/Applications/xampfiles/htdocs/test.php发送
警告:无法修改标头信息-标头已由第12行/Applications/XAMPP/examplepfiles/htdocs/test.php中的/Applications/xampfiles/htdocs/test.php发送
警告:无法修改标头信息-标头已由第13行的/Applications/XAMPP/examplepfiles/htdocs/test.php中的/Applications/XAMPP/xampfiles/htdocs/test.php发送
警告:无法修改标头信息-标头已由第14行的/Applications/XAMPP/examplepfiles/htdocs/test.php中的/Applications/XAMPP/xampfiles/htdocs/test.php发送
代码如下:
<?php
$file = './1966.xlsx';
echo "thanks";
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
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();
?>
我需要为整个脚本声明标题吗?我从php手册在线获得了header和readfile()部分。
您之所以会收到这些错误,是因为您在发送标题之前将内容发送到浏览器。
要解决此问题,需要删除echo "thanks";
。