notes icon indicating copy to clipboard operation
notes copied to clipboard

Phalcon getJsonRawBody(true) return null when post a valid json

Open lanlin opened this issue 6 years ago • 0 comments

情形

Phalcon 框架中的 getJsonRawBody(true) 方法,经常会返回 null 值。 即使 POST 的参数明明是个正常的 JSON 数据。

原因

查看过该方法的源代码,没有发现什么异常。

但是莫名其妙的就会在该方法内 json_decode() 时出现错误码为 4 的语法错误。 该错误表示传入的字符串不是一个正常的 JSON 字符串。

而且神奇的是,当我把该方法的代码由 Zephir 原样改写为 PHP 代码实现后,一切又正常了。

解决办法

由于该情况无法被重现,因此也没办法向 Phalcon 官方反应。 只能是自己写一个方法来覆盖掉原有的 getJsonRawBody,代码如下

/**
 *  Gets decoded JSON HTTP raw request body
 *
 * @param bool $associative
 * @return array|bool|mixed|\stdClass
 */
public function getJsonRawBody($associative = false)
{
    $rawBody = $this->getRawBody();

    if (empty($rawBody)) { return false; }

    $data = json_decode($rawBody, $associative);

    if (json_last_error() !== JSON_ERROR_NONE)
    {
        return false;
    }

    return $data;
}

lanlin avatar Sep 20 '19 06:09 lanlin