Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Content-Length header not working

I am trying to use this code to download a .zip file

<?php
    $file = "something.zip";
    $size = filesize($file);
    header('Content-type: application/octet-stream');
    header("Content-length: $size");
    header('Content-Disposition: attachment; filename="downloaded.zip"');
    readfile($file);
?>

but it does not seem to work, even when I try to set the filesize to a number like header("Content-length: 567247784");. I only get a file that either has no size declared, or a small file size like 28 bytes.

I looked at this question, and I think I have the same problem as the poster, but his solution is "there was a server problem". I think I also have a server configuration issue, but his answer does not help me at all.

like image 603
Nicolas Gnyra Avatar asked Jan 11 '14 16:01

Nicolas Gnyra


2 Answers

it has to do with mod_deflate getting in the way. I spent a day messing with .htaccess and trying a million different things, in the end this fixed it but I can't really explain why:

    header('Content-Length: '.$filesize);
    header("Content-Range: 0-".($filesize-1)."/".$filesize);

I want to add that my PHP was configured with less than 256MB of memory.

like image 137
TeeraMusic Avatar answered Sep 30 '22 21:09

TeeraMusic


I think the easiest and the best way is:

$head = array_change_key_case(get_headers($file, TRUE));
                    $filesize = $head['content-length'];
like image 37
Mohsen Abasi Avatar answered Sep 30 '22 20:09

Mohsen Abasi