0

I can't download files that already uploaded in my website, for example : I already uploaded a video file with 800mb file size and it is okay, the file is save to my directory in the File folder, then I want to download that file again, but as soon as I download the file, I will always got 1kb file not the exact size of the file, and when I play it, nothing happen

this is my code:

<?php
include 'db.php';
if(isset($_REQUEST['name'])) 
{
$var =$_REQUEST['name'];


$dir = "../files/"; 

$file = $dir . $var;



if(file_exists($file))
{

    header('Content-Description: File Transfer');
        header('Content-Type: video');
        header('Content-Disposition: attachment; 
filename='.basename($file));
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: ' . filesize($file));
        ob_clean();
        flush();
        readfile($file);
    mysqli_close($conn);
    exit();
}
else{
    echo "File not found";
}

}

?>  
  • Try to open the 1kb file in a text editor – Pratansyah Nov 22 '17 at 06:49
  • @Pratansyah this is log sir
    Fatal error: Out of memory (allocated 2097152) (tried to allocate 911990784 bytes) in C:\xampp\htdocs\DTI-KMS3\admin\functions\download.php on line 32
    – Warren Step Nov 22 '17 at 06:50
  • Well that's your problem. You're out of memory because the file that you read is being stored in the buffer. Have a look at this answer https://stackoverflow.com/a/31277949/2131856 I might also add that reading a file that big is a bad practice. Why don't you just give the user a link to the file? – Pratansyah Nov 22 '17 at 07:00
  • @Pratansyah thank your very much sir, Already Solved my Problem – Warren Step Nov 22 '17 at 07:25
  • This is the answer to my question credit to @Pratansyah https://stackoverflow.com/a/31277949/2131856 – Warren Step Nov 23 '17 at 01:50

1 Answers1

1

Yeah, I had the same problem too. After searching alot on the internet, I found out that the problem is related to output buffering. The following code solved my problem.

<?php
$file = $_GET['file'];


if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_end_clean();  //adding this line solves my problem
readfile($file);

exit;
?>

The code ob_end_clean() basically runs grabs everything in the buffer, then erases the buffer, and turns off output buffering.

shivamag00
  • 661
  • 8
  • 13