Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
274 views
in Technique[技术] by (71.8m points)

Can create zip archive in PHP, but cannot download it correctly2

I want to comment for this post "link" , but my reputation is lower tan 50, so I have to ask nearly the same question again.

I get the following error message from unzip (after downloading it from my website).

End-of-central-directory signature not found. Either this file is not a zipfile, or it constitutes one disk of a multi-part archive. In the latter case the central directory and zipfile comment will be found on the last disk(s) of this archive. unzip: cannot find zipfile directory in one of foo.zip or foo.zip.zip, and cannot find foo.zip.ZIP, period.

On my lampp server (testsetup) (at /opt/lampp/myprojects/tmp/foo.zip) unzip works perfect ( no error messages).

I am using this code:

$filename = 'foo.zip';
$path = '/opt/lampp/myprojects/tmp/foo.zip';
if(!file_exists($path))
{
    die('Error: file not found');
}
else {
    $handle = fopen($path, "r");
    header('Content-Description: File Transfer');
    header('Content-Type: application/zip');
    header('Content-Disposition: attachment; filename='.$filename);
    header('Content-Transfer-Encoding: binary');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Expires: 0');
    header('Pragma: public');
    header('Content-Length: ' . filesize($path));

    flush();
    readfile($path);
    fclose($handle);



  

Can anybody see my mistake and help me to solve this problems? I am trying to fix it for about 5h but I am not able to solve the problem.

question from:https://stackoverflow.com/questions/65927206/can-create-zip-archive-in-php-but-cannot-download-it-correctly2

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use the following to send your ZIP file to the user/browser. No reason to open it first.

ob_end_clean();
$FileBytes = filesize($temp_file);

header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename="WhateverYourFileNameIs.zip"');
header('Content-Length: ' . $FileBytes);

readfile($temp_file);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...