PHP 不解析 HTTP POST(压缩)JSON 请求?

标签 php json http

我有以下 PHP 文件:

<?php
    // ***************************************************
    if (!function_exists('gzdecode'))
    {
        function gzdecode($data) 
        {
            // strip header and footer and inflate
            return gzinflate(substr($data, 10, -8));
        }
    }
    // ***************************************************

    // get compressed (gzip) POST request into a string
    $comprReq = file_get_contents('php://input');

    // get decompressed POST request
    $decomprReq = gzdecode($comprReq);

    // decode to json
    $jsonData = json_decode($decomprReq, true);

    // create file if not exits or open file if exists
    $file = fopen('omni.json', 'a');

    if ($jsonData === null)
    {
        // mark as invalid and save. send HTTP response
        fwrite($file, 'invalid json');
        fclose($file);
        header('HTTP/1.0 400 Bad Request');
    }
    else 
    {
        // write json and save. send HTTP response
        fwrite($file, $jsonData);
        fclose($file);
        header('HTTP/1.0 200 OK');          
    }
?>

这个想法是它接受一个 JSON HTTP POST(压缩 - gzipped),解压缩它,并在新的(如果不存在)或现有的 json 文件的末尾附加 json(JSON 格式)。它还应根据结果发回 200 OK 或 400 BAD REQUEST HTTP 响应代码。

我尝试用 Postman 来测试它通过发送以下内容:

header (注意 gzip key ): enter image description here

示例 JSON 正文: enter image description here

结果: enter image description here

是的,没有任何反应。服务器上未创建任何 JSON 文件。响应始终为 200 OK。

知道我做错了什么吗?

最佳答案

检查您的文件路径和权限(使用 __DIR__ 指定文件名的完整路径)。变量 $decomprReq 为 false,因为您以明文形式发送内容而不是 gzip 压缩。 $comprReq 具有您发送的 json 值。我测试了您的代码,看起来没问题。

关于PHP 不解析 HTTP POST(压缩)JSON 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40333852/

相关文章:

php - 条件无效的 PDO 准备语句

php - Laravel wherebetween 不接受负数

c# - 我如何在 C# .NET(win7 手机)中读入 'nested' 和 'DataContractJsonSerializer' 的 Json 文件?

http - 我可以防止 Firefox 开发人员工具网络面板在页面重新加载时清除吗?

ios - 是否可以检索网站源代码以在 iPhone 应用程序中进行解析?

python - 使用 python 打印设置 header 访问控制允许来源

php - 如何解析 Mysql 存储过程中的 PHP Searilize 数据并循环它

javascript - Chrome 重复 ajax 请求或响应

json - 从 Cosmos DB 对象数组中选择值

json - 如何使用 Groovy 代码删除响应正文中 Gerrit 的 REST API 的魔术前缀?