dongxiqian2787 2013-12-04 21:09
浏览 73
已采纳

PHP处理一个zip文件,好像它是空的

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!
";
}

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?

  • 写回答

1条回答 默认 最新

  • doujieyu7062 2013-12-05 14:16
    关注

    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).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Python语言实验
  • ¥15 SAP HANA SQL 增加合计行
  • ¥20 用C#语言解决一个英文打字练习器,有偿
  • ¥15 srs-sip外部服务 webrtc支持H265格式
  • ¥15 在使用abaqus软件中,继承到assembly里的surfaces怎么使用python批量调动
  • ¥15 大一C语言期末考试,求帮助🙏🙏
  • ¥15 ch340驱动未分配COM
  • ¥15 Converting circular structure to JSON
  • ¥30 Hyper-v虚拟机相关问题,求解答。
  • ¥15 TSM320F2808PZA芯片 Bootloader