【问题标题】:PHP's 'gzuncompress' function in the shell? [duplicate]外壳中的 PHP 'gzuncompress' 函数? [复制]
【发布时间】:2012-02-07 21:51:20
【问题描述】:

可能重复:
Deflate command line tool

是的,我知道我可以在 shell 上使用 PHP 本身,但是我需要在 PHP 可用之前部署的脚本中的这个功能。

我尝试了gzipunzip,但要么我的参数不正确,要么他们只是不使用相同的压缩。

我想在 bash 脚本中使用它。进入更高级别的脚本语言不是一种选择。


出于测试目的,我编写了以下 PHP 脚本:

#!/usr/bin/php
<?
  $contents = file_get_contents( $argv[1] );
  $data = gzuncompress( $contents );
  echo substr( $data, 0, 20 ) . "\n";
?>

这会输出我所期望的(解码数据的开头)。

如果我将同一个文件传递给gunzip:

$ gunzip -c data
gzip: data: not in gzip format

如果我尝试unzip:

$ unzip data
Archive:  data
  End-of-central-directory signature not found.  Either this file is not
  a zipfile, or it constitutes one disk of a multi-part archive.  In the
  latter case the central directory and zipfile comment will be found on
  the last disk(s) of this archive.
unzip:  cannot find zipfile directory in one of data2 or
        data2.zip, and cannot find data2.ZIP, period.

按照建议,鉴于没有其他实用方法,我采用了related question 中提出的解决方案。
但鉴于我想避免转向另一种脚本语言(并引入另一种依赖项),我选择了所有这些语言:

_uncompressedData=
if hash perl 2>&-; then
  echo "Using Perl for decompression..." >&2
  _uncompressedData=$(perl -MCompress::Zlib -e 'undef $/; print uncompress(<>)' < compressed.bin || true)
elif hash ruby 2>&-; then
  echo "Using Ruby for decompression..." >&2
  _uncompressedData=$(ruby -rzlib -e 'print Zlib::Inflate.new.inflate(STDIN.read)' < compressed.bin || true)
elif hash php 2>&-; then
  echo "Using PHP for decompression..." >&2
  _uncompressedData=$(php -r "echo gzuncompress(file_get_contents('php://stdin'));" < compressed.bin || true)
elif hash python 2>&-; then
  echo "Using Python for decompression..." >&2
  _uncompressedData=$(python -c "import zlib,sys;print zlib.decompress(sys.stdin.read())" < compressed.bin || true)
else
  echo "Unable to find decompressor!" >&2
  exit 1
fi

这 4 个版本与我的测试用例产生了完全相同的输出。

【问题讨论】:

  • 你如何使用gzip?试试gzip -c /etc/motd | gunzip -c | diff /etc/motd -
  • 具有讽刺意味的是,两者 gzip zip 使用完全相同的算法。他们只是碰巧拥有的不仅仅是原始数据。

标签: php bash compression zlib


【解决方案1】:

gzuncompress 期望的格式是不带 gzip 标头的原始 zlib 格式。如果您使用 zlib 库的 C API,这是您默认获得的格式。

您可以使用zpipe 命令行实用程序解压缩此格式。此实用程序的源代码可在zlib 源代码分发中的examples/zpipe.c 中找到。但是这个程序默认没有编译安装。没有广泛部署的命令行实用程序接受原始 zlib 格式。

如果您想使用 PHP 的 gzip 格式(带有 gzipgunzip 处理的友好标题的格式),那么您需要使用 gzencodegzdecode 而不是 gzcompress & gzuncompress.

【讨论】:

  • 很遗憾,我不控制压缩数据。
  • 那么恐怕,即使你说这不是一个选项,你也必须考虑捆绑一个像zpipe 这样的实用程序或使用其中一种脚本语言来进行解压。 Ignacio Vazquez-Abrams 链接的Deflate command line tool 问题建议了 Python、Ruby 和 Perl 的方法。另外,您知道如何在 PHP 中进行操作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-31
  • 2013-01-07
  • 1970-01-01
  • 1970-01-01
  • 2020-12-13
  • 2019-09-25
相关资源
最近更新 更多