PHP readfile()破坏了文件

Kon*_*ler 5 php corrupt header readfile

在我的函数中,我正在下载一个将下载保存到日志文件的文件.每当我尝试下载上传的Excel文件时,Excel都会声明它已损坏.我的本地副本工作正常.这是我的download.php:

<?php
include_once 'includes/db_connect.php';
include_once 'includes/functions.php';

sec_session_start();
ob_start();
?>

<?php if (login_check($mysqli) == true) :?>
<?php
$logFile = "download.log";
$directory = "./downloads/";
date_default_timezone_set('America/New_York');

$filename = $_GET['file'];
$path = "$directory$filename";
if(file_exists($path) AND substr_count($filename,"/") == "0") {
  if (isset($logFile)) {
    $downloadLogRecord = $filename." || ".$_SESSION['name']." || ".$_SESSION['username']." || ".$_SERVER['REMOTE_ADDR']." || ".date('Y-m-d H:i:s')."\r\n";
    @file_put_contents($logFile,$downloadLogRecord,FILE_APPEND|LOCK_EX);
  }
  header("Content-type: application/octet-stream"); 
  header("Content-Disposition: attachment; filename=$filename"); 
  header("Content-Length: ".filesize($path));
  readfile("$path");
}
?>
<?php else : ?>
  <p>
    <span class="error">You are not authorized to access this page.</span> Please <a href="index.php">login</a>.
  </p>
<?php endif; ?>
Run Code Online (Sandbox Code Playgroud)

我怎样才能解决这个问题?

Kon*_*ler 13

弄清楚了.我只是在它ob_get_clean();之前readfile();ob_end_flush();之后添加.


Max*_*mus 10

请记住,您可以使用嵌套的输出缓冲区,这也会破坏您的下载(欢迎Vladamir为此搞清楚).因此,要ob_end_clean();在读取文件之前完全清除输出缓冲区(而不是仅运行),请运行此命令:

while (ob_get_level()) {
    ob_end_clean();
}   
Run Code Online (Sandbox Code Playgroud)

这将清除您的整个缓冲区,您将不会有任何额外的字符来搞乱您的下载.

  • 我花了几个小时寻找我的 zip 存档下载时损坏的原因。上帝保佑你,先生:) (2认同)