Issue reading HTTP request body from a JSON POST in PHP

微笑、不失礼 提交于 2019-11-26 01:59:55

问题


I\'m writing a script that is registered as an endpoint for a webhook. I know that it\'s successfully registered because I\'m writing the header of every request to my server logs. Here\'s a sample:

Content-Type: text/xml; charset=UTF-8
User-Agent: Jakarta Commons-HttpClient/3.1
Host: =={obfuscated}== 
Content-Length: 1918

The API that I\'ve registered with is POST-ing a JSON object to my script, and I\'d like to parse that object using PHP. As you can see from the request header, there\'s a nice big fat JSON object waiting to be parsed. It seems straightforward, but it hasn\'t been.

At first I tried using $_POST[\'json\'] or just $_POST but since the data isn\'t in an array, I wasn\'t really sure how to access it like that.

I\'ve tried using file_get_contents(\'php://input\') and fopen(\'php://input\', \'r\') with and without json_decode() but no luck. I can\'t use http_get_request_body() since the server I\'m on doesn\'t have PECL and that\'s out of my control.

Are there any other ways to interact with the POST-ed JSON object that I\'m missing? Thanks!


回答1:


Thanks to others for the input. It turns out that I just needed

$inputJSON = file_get_contents('php://input');
$input = json_decode($inputJSON, TRUE); //convert JSON into array

where the second parameter in json_decode returned the object as an array.

Hope this helps someone else!




回答2:


Even when the following works.

$inputJSON = file_get_contents('php://input');

If you want to continue using $_POST send the data as FormData

var fd = new FormData();
fd.append('key', 'value');
return axios.post('url', fd)


来源:https://stackoverflow.com/questions/7047870/issue-reading-http-request-body-from-a-json-post-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!