问题描述
我在用 PHP 下载文件时遇到问题。我有一个包含服务器根目录之外的文件的文件夹(出于安全原因,但我认为这可能不是问题),我正在尝试使用下面的脚本下载文件,
其中 $_POST['path']
或 $filename
(检查后)是我文件夹的绝对路径,例如
/home/username/storage/filename.extension
我的服务器根路径是 /home/username/www
当我尝试下载 .txt 文件时,似乎一切正常 - 我可以下载并打开它。
但是,当我下载图像或视频文件时,我计算机上的所有应用程序都无法打开该文件。
对于 .png,它说我的文件不是 PNG 文件,对于 .jpg,它说它不以 0x0a 0x0a
开头,等等。
每次我尝试下载某些内容时,我下载它的文件夹中文件的大小等于我下载的文件的大小.但是文件的格式/内容有问题。 我检查了我下载的目录中的文件,它们没有问题。问题仅在于下载的那些,所以由于某种原因我的脚本没有正确下载它们。
也许我的标题不正确?或者也许文件超过某个大小可能有问题(我的txt文件比图像小..,但即使是300M的视频也能在几秒钟内下载)? (但是,apache 错误日志中没有错误。)或者我做错了什么?
if(isset($_POST['path'])) {
//Read the filename
//+there are some checks on the path,to make sure user does not download a file which I dont want him to be able to download,but I dont think that is important,because the .txt file is downloaded normally
$filename = $_POST['path'];
//Check the file exists or not
if(file_exists($filename)) {
//Define header information
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header("Cache-Control: no-cache,must-revalidate");
header("Expires: 0");
header('Content-disposition: attachment; filename="'.basename($filename).'"');
header('Content-Length: ' . filesize($filename));
header('Pragma: public');
//Clear system output buffer
flush();
//Read the size of the file
readfile($filename);
//Terminate from the script
die();
}
else{
echo "File does not exist.";
}
}
else
echo "Filename is not defined."
解决方法
似乎在 ob_clean()
之前调用 readfile()
方法很有帮助:),
有关详细信息,请参阅 https://www.php.net/manual/en/function.ob-clean.php
这对我有用:
if(isset($_POST['path']))
{
//Read the filename
$filename = $_POST['path'];
//Check the file exists or not
if(file_exists($filename)) {
//Define header information
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header("Cache-Control: must-revalidate");
header('Content-Transfer-Encoding: binary');
header("Expires: 0");
header('Content-Disposition: attachment; filename="'.basename($filename).'"');
header('Content-Length: ' . filesize($filename));
header('Pragma: public');
ob_clean(); //<----- I had to add THIS LINE
//Clear system output buffer
flush();
//Read the size of the file
readfile($filename);
//Terminate from the script
die();
}
else{
echo "File does not exist.";
}
}
else
echo "Filename is not defined."