微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

用于下载文件的 PHP 脚本对 .txt 文件正常工作,但对图像或视频文件无效

如何解决用于下载文件的 PHP 脚本对 .txt 文件正常工作,但对图像或视频文件无效

我在用 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."

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。