ZIP file corrupted while loading header

I create a zip file via php about 2-3 MB, and in the end I want to send this zip file to the user for download.

Unfortunately, using the code below for some reason does not work. Well, it works, but not as intended. The file enters the browser as it should. I download it, open it, but when I try to extract or view the files inside it, it will break, saying that it is damaged. If, however, I go and open a file that exists in the zip file directory, it opens fine, and I can exract-view everything there. Any ideas why this is happening?

if (headers_sent()) { echo 'HTTP header already sent'; } else { if (!is_file($zip_name)) { header($_SERVER['SERVER_PROTOCOL'].' 404 Not Found'); echo 'File not found'; } else if (!is_readable($zip_name)) { header($_SERVER['SERVER_PROTOCOL'].' 403 Forbidden'); echo 'File not readable'; } else { header($_SERVER['SERVER_PROTOCOL'].' 200 OK'); header("Content-Type: application/zip"); header("Content-Transfer-Encoding: Binary"); header("Content-Length: ".filesize($zip_name)); header("Content-Disposition: attachment; filename=\"".$zip_name."\""); readfile($zip_name); } } 
0
php zip
Jul 02 '14 at 11:26
source share
1 answer

Try adding exit (); at the end of the script. Is it possible that the script inadvertently sends spaces after readfile () commands, such as spaces after ? >

It is also useful to use ob_start () ob_clean () functions.

  ob_start(); // .... some code header($_SERVER['SERVER_PROTOCOL'].' 200 OK'); header("Content-Type: application/zip"); header("Content-Transfer-Encoding: Binary"); header("Content-Length: ".filesize($zip_name)); header("Content-Disposition: attachment; filename=\"".$zip_name."\""); // disable cache header('Expires: ' . gmdate('D, d MYH:i:s') . ' GMT'); header("Cache-control: private"); header('Pragma: private'); ob_end_clean(); readfile($zip_name); exit(); 
+1
Jul 02 '14 at 12:11
source share



All Articles