ZIP file corrupted when downloaded by header [duplicate]
Asked Answered
S

1

0

I'm creating a zip file through php around 2-3mbs and at the end i want to send that zip file to the user for download.

Unfortunately using the below does not work for some reason. Well it works but not as it was supposed to. The file gets to the browser as it should. I download it, open it but when i try to exract or view the files inside it breaks down saying it's corrupted. If however i go and open the file that exists in the directory zip file opens fine and i can exract-view everything there. Any ideas why is this 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);
    }
}
Sobel answered 2/7, 2014 at 11:26 Comment(1)
What is the value of $zip_name?Expectant
V
2

Try add exit(); on the end of script. It is possible that script send inadvertently whitespace after commands readfile(), for example whitespace after the ?>

It is also suitable 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 M Y H:i:s') . ' GMT');
    header("Cache-control: private");
    header('Pragma: private');

    ob_end_clean();
    readfile($zip_name);

    exit();      
Vandalism answered 2/7, 2014 at 12:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.