Header ('Content-type: application / octet-stream') calls files with 0 bytes

I am using a database query in PHP to get a binary file. But when I try to download it, the header (line Content-type: application / octet-stream) calls 0 byte files. Without this line, I can upload a file with full content. This is a binary that is accurate, so I just can't figure out why this line is causing 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.

+6
source share
2 answers

filesize() will not return a meaningful value.

You have binary data in $file , not the actual file name as needed as the first parameter. Therefore, you will get an error. (Enable error_reporting! Do not see errors, and not have two different things.)

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

Btw, application/octet-stream or other fills cannot be used to force download. This is the Content-Disposition: header, which is most important for this. You can still send the correct MIME type.

+5
source

From looking at the query, I assume that binary data is stored in $row['data'] . To set the correct Content-Length header, you must use mb_strlen($row['data']); . If multibyte support (mb_ functions) is not activated on your computer, use the strlen () parameter. But keep in mind that this can lead to akward results, because binary data can actually contain an EOF byte sequence and return too short a length. With the mb_strlen function, you are on the save side.

+1
source

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


All Articles