【问题标题】:PHP json_decode returns null, even though the json is validPHP json_decode 返回 null,即使 json 是有效的
【发布时间】:2018-07-11 15:31:39
【问题描述】:
<?php

    require_once('config.php'); //connection info

    $array = array();
    // var_dump($array);

    $json = file_get_contents("php://input");

    if (empty($json)){
        //theres no data; do nothing
        // $file = fopen("log.txt","a");
        // fwrite($file, "no data");
        // fclose($file);
    } else {
        //using a file because json_decode doesn't work from what ever data is being pulled from the webhook

        $myfile = fopen("log.txt", "w") or die("Unable to open file!"); 
        //open file for writing. use w so that it erases old data every time before it adds new data

        // $data =  fread($myfile,filesize("logs.txt"));
        // fwrite($myfile, $json);

        // This will remove unwanted characters.
        // Check http://www.php.net/chr for details

        for ($i = 0; $i <= 31; ++$i) { 
            $json = str_replace(chr($i), "", $json); 
        }
        $json = str_replace(chr(127), "", $json);

        // This is the most common part
        // Some file begins with 'efbbbf' to mark the beginning of the file. (binary level)
        // here we detect it and we remove it, basically it's the first 3 characters 
        if (0 === strpos(bin2hex($json), 'efbbbf')) {
           $json = substr($json, 3);
        }

        fwrite($myfile, $json); //write the stripped version of the json
        $data = json_decode($json, true);
        fwrite($myfile, print_r($data, true));

        // print_r($json);
        array_push($array, $data); //add data to array variable. This is not neccesary, but it was used during testing phase.

        $url = /*"http://localhost:5984/incoming";*/"https://gel.freshservice.com"; //this is the response url

        switch (json_last_error()) { //this was for testing the json data from freshservice
            case JSON_ERROR_NONE:
                echo ' - No errors';
                fwrite($myfile, ' - No errors');
            break;
            case JSON_ERROR_DEPTH:
                echo ' - Maximum stack depth exceeded';
                fwrite($myfile, ' - Maximum stack depth exceeded');
            break;
            case JSON_ERROR_STATE_MISMATCH:
                echo ' - Underflow or the modes mismatch';
                fwrite($myfile, ' - Underflow or the modes mismatch');
            break;
            case JSON_ERROR_CTRL_CHAR:
                echo ' - Unexpected control character found';
                fwrite($myfile, ' - Unexpected control character found');
            break;
            case JSON_ERROR_SYNTAX:
                echo ' - Syntax error, malformed JSON';
                fwrite($myfile, ' - Syntax error, malformed JSON');
            break;
            case JSON_ERROR_UTF8:
                echo ' - Malformed UTF-8 characters, possibly incorrectly encoded';
                fwrite($myfile, ' - Malformed UTF-8 characters, possibly incorrectly encoded');
            break;
            default:
                echo ' - Unknown error';
                fwrite($myfile, ' - Unknown error');
            break;
        }

        $meta = ["received" => time(),
        "status" => "new",
        "agent" => $_SERVER['HTTP_USER_AGENT']];

        $options = ["http" => [
        "method" => "POST",
        "header" => ["Content-Type: application/json"],
        "content" => json_encode(["data" => $data, "meta" => $meta])]
        ];

        $context = stream_context_create($options);
        $response = file_get_contents($url, false, $context); //http_response_code()

        //Do something with the array now
?>

如果我创建一个读取 txt 文件的随机 php 并在文件中的数据上使用 json_decode,这可以正常工作,但是一旦我使用 php://input,它就会返回 NULLjson_last_error() 也不会返回任何错误。

【问题讨论】:

  • 发布带有echo $json;的页面的查看源代码副本
  • php://input 的内容是什么?
  • 如果 JSON 是有效的,你为什么要摆弄它?
  • 另外,为什么你的json_last_error() 在实际json_decode() 之后进行测试
  • json_last_error() 将不返回任何内容,如果没有给json_decode()。所以问题是阅读php://input 不是您的json 的来源。

标签: php json webhooks


【解决方案1】:

你是如何向 php 脚本提供数据的?

我看到的唯一一件事是你缺少一个右花括号} 最后为if (empty($json)) 关闭您的else 案例。 (//Do something with the array now之后)

据我所知,添加大括号后,代码对我有效。 (日志被写入等)

【讨论】:

  • 那一定是复制错误,否则代码甚至无法运行,因此无法返回null
  • 这是我的想法,虽然我已经测试了代码。它运行“正确”(据我所知, var_dump() 正在生成解码的 json 结构)。我没有连接设置的包含,我不知道来自客户端的输入数据是否有问题,或者某些服务器配置是否阻碍脚本正确执行 OP。
猜你喜欢
  • 2011-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-27
  • 2019-04-27
相关资源
最近更新 更多