0

I'm trying to create a webhook to send JSON encoded data to a users webhook receiver.

This is how I send the data:

$url = 'https://www.example.com/user-webhook-receiver.php';
    $data = array('title' => 'Hello',
    'message' => 'World',
    'url' => 'http://example.com/#check');

    $content = json_encode($data);

    $curl = curl_init($url);
            curl_setopt($curl, CURLOPT_HEADER, false);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($curl, CURLOPT_HTTPHEADER,
                    array("Content-type: application/json"));
            curl_setopt($curl, CURLOPT_POST, true);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $content);

            $json_response = curl_exec($curl);

How can the user access the data I sent him? I tried this, but there is no content in it:

$data = json_decode($_POST);

How to access the data?

Uli
  • 2,625
  • 10
  • 46
  • 71

2 Answers2

0

See this question for how you need to encode the CURLOPT_POSTFIELDS.

You need to do something like:

$postdata = "content=" . urlencode($content);

On the sending side.

Then on the receiving side:

$content = $_POST['content']; 
$content = urldecode($content);
$json_content = json_decode($content);

Although, I agree with the comment above that you should just send the array. What's the point of JSON encoding it you're POSTING the data?

EDIT: to just send the array you would do:

curl_setopt($curl, CURLOPT_POSTFIELDS, $data);

(but see the question I linked to for more details on how to do it with URL encoding)

On the receiving side, you would do:

$title = $_POST['title'];
$message = $_POST['message'];
Community
  • 1
  • 1
pocketfullofcheese
  • 8,427
  • 9
  • 41
  • 57
0

To read raw POST data in php, you can do the following:

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

It's also possible to pass an associative array directly to curl_setopt($curl, CURLOPT_POSTFIELDS, $content); - if you do that, PHP will be able to automatically convert it back to an array in $_POST on the receiving end.

Sam Dufel
  • 17,560
  • 3
  • 48
  • 51