Alex Rivera | Logout

header('Content-type: application/octet-stream') cause 0 byte files

Asked 2012-06-24T08:06:46.897
9

I'm using database query in PHP to retrieve a binary file. But when I'm trying to force download it, the header('Content-type: application/octet-stream') line cause 0 byte files. Without that line I can download the file with full content. It's a binary file that's for sure so I just can't understand why that line causes the problem. The code:

$result = mysql_query("SELECT data FROM stored_file WHERE file_name = '$q'");

while($row = mysql_fetch_array($result))
{
    $file = $row['data'];
}


    header('Content-disposition: attachment; filename='.$q);
    header('Content-type: application/octet-stream');
    header('Content-Length: '.filesize($file));
    header("Pragma: no-cache");
    header("Expires: 0");
    echo $file;

Any idea? Thanks.

Edit
Report

1 Answer

6

filesize() won't return a meaningful value.

You have binary data in $file, not an actual filename as required as first parameter. Hence you would get an error. (Enable error_reporting! Not seeing errors, and not having them are two different things.)

So what you want to use there is strlen($file), not filesize().

Btw, application/octet-stream or other fill-ins have no use for forcing downloads. It's the Content-Disposition: header which is most crucial to that effect. You're still allowed to send the correct MIME type.

answered 2012-06-24T10:40:21.837

Your Answer