73

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!

Hartley Brody
  • 8,669
  • 14
  • 37
  • 48
  • 1
    The content-type for the JSON body is wrong, so it might have been removed. But try [`$HTTP_RAW_POST_DATA`](http://php.net/manual/en/reserved.variables.httprawpostdata.php) – mario Aug 13 '11 at 01:18
  • @mario I've seen that variable before, but wasn't sure how to use it. json_decode($HTTP_RAW_POST_DATA); didn't work – Hartley Brody Aug 13 '11 at 01:23
  • See the manual page. It needs to be enabled in the `php.ini` first. Also did you try with the correct MIME type yet? mod_security enabled by any chance? – mario Aug 13 '11 at 01:24

2 Answers2

203

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.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Hartley Brody
  • 8,669
  • 14
  • 37
  • 48
  • 10
    Works for me, too. Just can't believe that JSON data is not recognized by PHP. I understand that it is raw data type after all, but still... – Mladen Janjetovic Mar 04 '15 at 10:22
  • 6
    `$_POST` is only filled with values when receiving a request body with the `application/x-www-form-urlencoded` or `multipart/form-data` **Content-Type** header. Due to the stream nature of PHP's request body, you will either get data in `$_POST` ***or*** the input stream, not both. – Nick Bedford Jun 30 '17 at 04:18
5

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)