Skip to content
Advertisement

Force file download with header is corrupting file

So I am using PHP headers to force download a file, but when the file is saved it gets corrupted because for whatever reason the HTML code from the download page is also added into the file code/contents:

Beginning of downloaded file:

End of downloaded file: enter image description here

and here is my code that forces the download, I also downloaded the same file straight from my server (FTP) and it does not have this in its file code, so I know it has to be the following code causing the problem:

header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename={$qfile['rfname']}");
header("Content-Type: application/zip");
header("Content-Transfer-Encoding: binary");
readfile($file['dl_path']);

I’ve looked around but I don’t see anything pertaining to this, would anybody have an idea as to why this could be happening?

Advertisement

Answer

Like Barmar said, I needed to exit();/die(); after the function readfile();.

So the fix would look like:

header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename={$qfile['rfname']}");
header("Content-Type: application/zip");
header("Content-Transfer-Encoding: binary");
readfile($file['dl_path']);s
// die(); - Either one
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement