ZLIB inflate在PHP中给出“数据错误”

时间:2013-06-10 10:36:38

标签: php zlib inflate

我有一个文件,其中zlib deflate d块为4096字节。我可以使用Minzip的inflate实现使用C ++扩充至少1个4096字节的块,而不会出现乱码文本或data error

我正在使用以下C ++实现来扩充数据:

#define DEC_BUFFER_LEN 20000
int main(int argc, char* argv[]) {
    FILE *file = fopen("unpackme.3di", "rb");

    char *buffer = new char[4096];

    std::fstream outputFile;
    outputFile.open("output.txt", std::ios_base::out | std::ios_base::trunc | std::ios_base::binary);


    // Data zit nu in de buffer
    char *decbuffer = new char[DEC_BUFFER_LEN];

    mz_streamp streampie = new mz_stream();

    streampie->zalloc = Z_NULL;
    streampie->zfree = Z_NULL;
    streampie->opaque = Z_NULL;
    streampie->avail_in = Z_NULL;
    streampie->next_in = Z_NULL;

    if (inflateInit(streampie) != Z_OK)
        return -1;

    fread(buffer, 1, 4096, file);

    streampie->next_in = (Byte *)&buffer[0];
    streampie->avail_in = 4096;

    streampie->next_out = (Byte *)&decbuffer[0];
    streampie->avail_out = DEC_BUFFER_LEN;

    streampie->total_out = 0;

    int res = inflate(streampie, Z_NO_FLUSH);

    if (res != Z_OK && res != Z_STREAM_END) {
        std::cout << "Error: " << streampie->msg << std::endl;
        return;
    }
    outputFile.write(decbuffer, streampie->total_out); // Write data to file

    fclose(file);

    inflateEnd(streampie);

    outputFile.flush();
    outputFile.close();

    getchar();

    return 0;
}

我正在使用以下PHP实现:

function Unpack3DI($inputFilename) {
    $handle = fopen($inputFilename, 'rb');
    if ($handle === false) return null;

    $data = gzinflate(fread($handle, 4096));
    return $data;
}


var_dump(Unpack3DI('unpackme.3di'));

结果:

Warning: gzinflate() [function.gzinflate]: data error in /var/www/html/3di.php on line 9
bool(false)

1 个答案:

答案 0 :(得分:2)

问题是我使用了错误的功能。我必须使用gzuncompress而不是gzinflate。 另外,推送gzuncompress中的整个文件实际上完成了这项工作,因为zlib会检查是否有剩余的块要解压缩。

有关PHP中Zlib方法的更多信息,请参见this answer to "Which compression method to use in PHP?"