Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Get JSON POST Data

Tags:

json

http

php

I've setup a Webhook to get notifications posted to a PHP page on my server. The notification request to my server is like this:

POST /message/receive HTTP/1.1
Host: http://www.yoururl.com/zipwhip/api/receive
Content-Length: 581
Content-Type: application/json; charset=UTF-8

{ "body":"Thanks for texting, this is an auto reply!",
  "bodySize":42,
  "visible":true,
  "hasAttachment":false,
  "dateRead":null,
  "bcc":null,
  "finalDestination":"4257772300",
  "messageType":"MO",
  "deleted":false,
"statusCode":4,
"id":634151298329219072, "scheduledDate":null, "fingerprint":"132131532", "messageTransport":9, "contactId":3382213402, "address":"ptn:/4257772222",
"read" "dateCreated":"2015-08-19T16:53:45-07:00", "dateDeleted":null,
  "dateDelivered":null,
  "cc":null,
  "finalSource":"4257772222",
} "dev

I've tried using the following to convert the JSON data to a string that I can work with, but I'm getting nothing so far:

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

Everything I've read indicates this should work - I tested the following and this is actually working:

$webhookContent = "";

    $webhook = fopen('php://input' , 'rb');
    while (!feof($webhook)) {
        $webhookContent .= fread($webhook, 4096);
    }
    fclose($webhook);

I'm trying to understand why file_get_contents('php://input'); doesn't work when everything I've read indicates that's the function I should be using, and why fopen('php://input' , 'rb'); works instead?

If I do var_dump($inputJSON) I get:

    string(527) "{ "body":"Thanks for texting, this is an auto reply!",
  "bodySize":42,
  "visible":true,
  "hasAttachment":false,
  "dateRead":null,
  "bcc":null,
  "finalDestination":"4257772300",
  "messageType":"MO",
  "deleted":false,
"statusCode":4,
"id":634151298329219072, "scheduledDate":null, "fingerprint":"132131532", "messageTransport":9, "contactId":3382213402, "address":"ptn:/4257772222",
"read" "dateCreated":"2015-08-19T16:53:45-07:00", "dateDeleted":null,
  "dateDelivered":null,
  "cc":null,
  "finalSource":"4257772222",
}"

var_dump($input) returns NULL

like image 489
user982124 Avatar asked Dec 18 '22 12:12

user982124


1 Answers

The following is working for me now:

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

I think my issue was using:

$input= json_decode( $inputJSON, TRUE ); 

instead of just:

$input= json_decode( $inputJSON ); 
like image 139
user982124 Avatar answered Jan 06 '23 06:01

user982124