PHP readfile () corrupts file

In my function, I upload a file that saves the downloads to a log file. Whenever I try to download a downloaded Excel file, Excel claims that it is damaged. My local copy is working fine. Here is my download.php file:

<?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; ?>

How can i fix this?

+4
source share
3 answers

Figured it out. I just added ob_get_clean();before readfile();and ob_end_flush();after it.

+12
source

, , ( , ). , ( ob_end_clean();), , :

while (ob_get_level()) {
    ob_end_clean();
}   

, , .

+7

: PDF , , , , :

die(); exit(); , MVC Framework, MVC .

: , , readfile(FILE_NAME)

0

Source: https://habr.com/ru/post/1530335/


All Articles