2013-12-04 21:09
浏览 62


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

$url = "";

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

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

    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!!!


    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?

图片转代码服务由CSDN问答提供 功能建议


  $ url =“";

 $ zip_file_contents = file_get_contents($ url); 
file_put_contents(“”,$ zip_file_contents); 
 $ zip = zip_open(“”); 
if(is_resource($ zip))
 while($ zip_entry = zip_read($ zip))
 if if(zip_entry_open($ zip,$ zip_entry,'r'))
 $ buf = zip_entry_read  ($ zip_entry,zip_entry_filesize($ zip_entry)); 
 / * 
用$ buf做的东西!!! 
 * / 
 zip_entry_close($ zip_entry); 
 \  n zip_close($ zip); 

所以:获取文件,将其保存到磁盘,解压缩以提取其中包含的文件,对文件执行操作。 这里的问题是,由于某些原因我无法弄清楚, zip_read 返回 FALSE ,好像它无法读取ZIP存档中的文件。 $ zip 确实包含一个资源,我已经用 var_dump 进行了检查。

这让我更加陌生的是我下载了ZIP 使用顶部的URL在我的PC上文件,手动将其上传到PHP服务器,并注释掉对 file_get_contents file_put_contents 的调用,以便PHP使用本地版本。 当我这样做时, zip_read 正确地在ZIP中找到适当数量的文件,处理按预期进行。

我也试过这样做: $ zip = zip_open($ url) $ zip 未通过 is_resource($ zip)检查。

Something 我的代码显然是错误的,因为URL工作并返回一个有效的ZIP存档。 它是什么?

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

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 :

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

    解决 无用
    打赏 举报

相关推荐 更多相似问题