[英]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_read
返回FALSE
,好像无法读取ZIP存档中的文件。 $zip
does contain a resource, I've checked with var_dump
. $zip
确实包含资源,我已经检查了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. 令我感到奇怪的是,我使用顶部的URL将ZIP文件下载到PC上,手动将其上传到PHP服务器,并注释掉对
file_get_contents
和file_put_contents
的调用,因此PHP使用本地版本。 When I do this, zip_read
correctly finds the right amount of files inside the ZIP and processing proceeds as it should. 当我这样做时,
zip_read
可以在ZIP内正确找到正确数量的文件,并按需要进行处理。
I also tried doing this : $zip = zip_open($url)
but $zip
fails the is_resource($zip)
check. 我也尝试这样做:
$zip = zip_open($url)
但是$zip
无法通过is_resource($zip)
检查。
Something is obviously wrong with my code since the URL works and returns a valid ZIP archive. 我的代码显然有问题,因为该URL有效并返回了一个有效的ZIP存档。 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.
遵循@diolemo的建议,我在十六进制编辑器中打开了服务器的ZIP存档。 Here's what I found at the top, followed by the usual ZIP binary data : http://pastebin.com/vQEXJtTN
这是我在顶部找到的,然后是常规的ZIP二进制数据: http : //pastebin.com/vQEXJtTN
It turns out there was a PHP error mixed in with the actual content of the ZIP file. 事实证明,ZIP文件的实际内容中混入了一个PHP错误。 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!
不确定如何解决此问题(但肯定知道它与HTTP标头有关),我尝试了此人的代码,而且,您知道我的代码现在可以正常工作了!
Lessons learned? 得到教训? Never trust your data, even if it seems all right (both 7-Zip and Winrar managed to open the file without problem).
即使看起来没问题,也不要信任您的数据(7-Zip和Winrar都成功打开了文件)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.