简体   繁体   中英

PHP downloading .zip file but incorrectly

I am trying to download a zip file from a local server on to the HD.

$zip = new ZipArchive;
$zip->open($archive, ZipArchive::CREATE);

$files = scandir($dir);
unset($files[0], $files[1]);
foreach ($files as $file) {
$zip->addFile($dir.'/'.$file);
}
$zip->close();
$download=$archive;
header("Content-Disposition: attachment; filename=\"Reports". $stocktake_id. ".zip");
header("Pragma: public");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");

The file gets downloaded but the size of it is incorrect and it doesn't open properly, saying that the format is either invalid or file is corrupted.

I think you are missing the content-type header. Also, I don't see you echo'ing the raw data to the clientside? And, make sure there is not debug output or anything that is not in the file itself.

//After you saved your file:

download_file_to_client($saved_file);
exit;

function download_file_to_client($file, $mime = 'application/zip')
{
    $filesize = filesize($file);
    header('Content-Type: '.$mime.';charset=utf-8');
    header('Content-Disposition: attachment;filename="some-filename.zip"');
    header('Pragma: no-cache');
    header('Expires: 0');
    header('Content-Length: ' . $filesize);
    flush(); // Get the headers out immediately to prevent any delay in some browsers.

    $fh = fopen($file, "r");
    while ($fh && !feof($fh))
    {
        echo fread($fh, 8192);
    }
    fclose($fh);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM