4

I have this cURL function that send json to a REST API:

$url = "https://server.com/api.php";
$fields = array("method" => "mymethod", "email" => "myemail");

$result = sendTrigger($url, $fields);

function sendTrigger($url, $fields){  
    $fields = json_encode($fields);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json; charset=UTF-8"));
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $curlResult["msg"] = curl_exec($ch);
    $curlResult["http"] = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    return $curlResult;
}

On the server, I have this code:

$data = json_decode($_REQUEST);
var_dump($data);
exit();

When I execute the cURL command it returns me this:

Warning:  json_decode() expects parameter 1 to be string, array given in

How's that?

Thanks.

4
  • Mixed up json_encode with json_decode? Commented Oct 3, 2013 at 20:49
  • 1
    possible duplicate of How to get body of a POST in php? Commented Oct 3, 2013 at 20:49
  • 3
    Because $_REQUEST is most always an array, even if empty. Your JSON blob doesn't appear in there, but php://input. Commented Oct 3, 2013 at 20:49
  • Do you mean $result, not $_REQUEST? Commented Oct 3, 2013 at 20:52

2 Answers 2

11

If you are not using one of the form-encoded content types, PHP will not populate data into $_POST.

You need to get your JSON payload from PHP raw input like this:

$json = file_get_contents('php://input');
$array = json_decode($json);
Sign up to request clarification or add additional context in comments.

Comments

0

In PHP json_decode takes a string and converts it into an object. The $_REQUEST variable is a global variable that contains the contents of $_GET, $_POST, and $_COOKIE (see PHP reference). Most likely, you have a typing error in your code and you probably meant to use $request instead of $_REQUEST.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.