EDIT: A more modern take on this topic is here http://www.lornajane.net/posts/2018/make-a-post-request-from-php-with-guzzle
We can’t send post fields, because we want to send JSON, not pretend to be a form (the merits of an API which accepts POST requests with data in form-format is an interesting debate). Instead, we create the correct JSON data, set that as the body of the POST request, and also set the headers correctly so that the server that receives this request will understand what we sent:
$data = array("name" => "Hagrid", "age" => "36"); $data_string = json_encode($data); $ch = curl_init('http://api.local/rest/users'); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json', 'Content-Length: ' . strlen($data_string)) ); $result = curl_exec($ch);
All these settings are pretty well explained on the curl_setopt() page, but basically the idea is to set the request to be a POST request, set the json-encoded data to be the body, and then set the correct headers to describe that post body. The
CURLOPT_RETURNTRANSFER is purely so that the response from the remote server gets placed in
$result rather than echoed. If you’re sending JSON data with PHP, I hope this might help!