如何在PHP/Lumen/Laravel中解压Gzip请求?

4

我收到了一个第三方的请求,其中包含gzip编码的文本(大约1MB,所以很有道理)。

我的测试路由:

$router->post(
    'testgzip',
    function (\Illuminate\Http\Request $request) {
        $decompressed = null;
        if ($request->header('content-encoding') === 'gzip') {
            $decompressed = gzinflate($request->getContent());
        }

        return [
            'body' => $decompressed ?? $request->getContent(),
        ];
    }
);

我的测试文件test.txt

hello world!

我的健全性检查:
curl --data-binary @test.txt -H "Content-Type: text/plain" -X POST http://localhost:8000/testgzip 
{"body":"hello world!"}    

为了压缩它,我运行以下命令:gzip test.txt 我的curl:
curl --data-binary @test.txt.gz -H "Content-Type: text/plain" -H "Content-Encoding: gzip" -X POST http://localhost:8000/testgzip

触发

gzinflate(): 数据错误

我也尝试了gzuncompress,但会触发

gzuncompress(): 数据错误

我做错了什么?如何解压缩gzip请求?

2个回答

7

如果需要解压缩gzipped内容,您需要使用gzdecode()函数。

$decompressed = gzdecode($request->getContent());

这是PHP内置的功能。

gzinflate() 处理解压缩(而非gzip格式)的字符串,而gzuncompress() 处理压缩的字符串(而非gzip格式)。

相关文档:


谢谢!这些术语对我来说似乎是可以互换的,特别是因为所有函数都以gz开头。 - Moak
@Moak 即使使用gzdecode(),我仍然收到“数据错误”的错误信息。 - Paranoid Android

0

这一个对我有效

gzuncompress(base64_decode($request->getContent()));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接