简体   繁体   中英

PHP handles a zip file as if it's empty

Here's a very stripped down version of the code I'm using.

$url = "http://server.com/getDaFile";

//Get the file from the server
$zip_file_contents = file_get_contents($url);
//Write file to disk
file_put_contents("file.zip", $zip_file_contents);

//open zip file
$zip = zip_open("file.zip");

if(is_resource($zip))
{
    while($zip_entry = zip_read($zip))
    {
        if(zip_entry_open($zip, $zip_entry, 'r'))
        {
            //Read the whole file
            $buf = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));

            /*
            Do stuff with $buf!!!
            */

            zip_entry_close($zip_entry);
        }
    }

    zip_close($zip);
}
else
{
    echo "Not a resource. Oh noes!\n";
}

So : get the file, save it to disk, unzip it to extract files it contains, do stuff with files. The problem here is that, for some reason I cannot figure out, zip_read returns FALSE , as if it couldn't read files inside the ZIP archive. $zip does contain a resource, I've checked with var_dump .

What makes this even stranger is that I downloaded the ZIP file on my PC using the URL on top, manually uploaded it to the PHP server, and commented out the calls to file_get_contents and file_put_contents so PHP uses the local version. When I do this, zip_read correctly finds the right amount of files inside the ZIP and processing proceeds as it should.

I also tried doing this : $zip = zip_open($url) but $zip fails the is_resource($zip) check.

Something is obviously wrong with my code since the URL works and returns a valid ZIP archive. What is it?

So I finally found out the problem. Following @diolemo's suggestion, I opened my server's ZIP archive in a hex editor. Here's what I found at the top, followed by the usual ZIP binary data : http://pastebin.com/vQEXJtTN

It turns out there was a PHP error mixed in with the actual content of the ZIP file. Unsure of how to fix this (but knowing it certainly had to do with HTTP headers), I tried this guy's code and, what do you know, my code works perfectly now!

Lessons learned? Never trust your data, even if it seems all right (both 7-Zip and Winrar managed to open the file without problem).

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