Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP readfile() corrupts file

In my function I'm downloading a file that saves downloads to a log file. Whenever I try to download an Excel file I uploaded, Excel states that it is corrupted. My local copy works fine. Here is my 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; ?>

How can I fix this?

like image 371
Konstantin Keller Avatar asked Mar 05 '14 23:03

Konstantin Keller


1 Answers

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

like image 152
Konstantin Keller Avatar answered Oct 06 '22 22:10

Konstantin Keller