Receive JSON POST with PHP

前端 未结 7 2331
Happy的楠姐
Happy的楠姐 2020-11-21 04:42

I’m trying to receive a JSON POST on a payment interface website, but I can’t decode it.

When I print :

echo $_POST;

I get:

7条回答
  •  北荒
    北荒 (楼主)
    2020-11-21 05:25

    It is worth pointing out that if you use json_decode(file_get_contents("php://input")) (as others have mentioned), this will fail if the string is not valid JSON.

    This can be simply resolved by first checking if the JSON is valid. i.e.

    function isValidJSON($str) {
       json_decode($str);
       return json_last_error() == JSON_ERROR_NONE;
    }
    
    $json_params = file_get_contents("php://input");
    
    if (strlen($json_params) > 0 && isValidJSON($json_params))
      $decoded_params = json_decode($json_params);
    

    Edit: Note that removing strlen($json_params) above may result in subtle errors, as json_last_error() does not change when null or a blank string is passed, as shown here: http://ideone.com/va3u8U

提交回复
热议问题