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 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示