【问题标题】:PHP not parsing HTTP POST (compressed) JSON request?PHP不解析HTTP POST(压缩)JSON请求?
【发布时间】:2016-10-30 21:33:32
【问题描述】:

我有以下 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 进行测试:

标题(注意 gzip 密钥):

示例 JSON 正文:

结果:

是的,没有任何反应。没有在服务器上创建 JSON 文件。响应总是 200 OK。

任何想法我做错了什么?

【问题讨论】:

  • 检查您在服务器和文件路径中的权限。可能是apache没有创建文件的权限。
  • 刚刚做了,看起来不错。我也尝试自己创建omni.json(空),这样PHP就可以打开并写入它而无需创建它。
  • 你能检查一下使用的函数 fopen() 或 fwrite() 是否返回 false 吗?
  • 您使用您的用户权限创建文件,如果 apache 尝试附加一些文本,则可能没有权限。使用 chmod 777 omni.json

标签: php json http


【解决方案1】:

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

【讨论】:

  • 实际上权限很好。问题是代码(例如没有右斜杠的注释行,例如没有 */ 的 /****)
  • 在代码中我看到 // *** 与 //** 不同。
猜你喜欢
  • 2012-01-13
  • 1970-01-01
  • 2013-12-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多