PHP - Curl

php

How can we make a request using CURL?

First create a curl object by invoking curl_init(), set various options using the curl_setopt, invoke curl_exec which would perform the request and return the result. Finally, we need to invoke curl_close($curl) to destroy or release the resource associated with the $curl object:

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($curl);
curl_close($curl);

What are various CURL options?

  1. CURLOPT_URL: Specify the URL end-point for this request.
  2. CURLOPT_POST: Indicates that this should be a POST request.
  3. CURLOPT_POSTFIELDS: Specify the POST data for this request.
  4. CURLOPT_RETURNTRANSFER: Specify that the return result should be the raw data.

See http://php.net/manual/en/function.curl-setopt.php

How can we use CURL to post JSON?

$data = array("name" => "Hagrid", "age" => "36"); 
$ch= curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");                                                                     
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));                                                                  
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);
curl_close($curl);

In the above code, the curl_exec line returns result and we can parse the result in PHP:

$jsonResult = json_decode($result,true);

How can we send custom request headers using CURL?

We can send custom request headers by specifying the CURLOPT_HTTPHEADER option with an array:

curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
    'Content-Type: application/json',                                                                                
    'Content-Length: ' . strlen($data_string))                                                                       
);

How can we use the curl command line utility to call a REST service?

curl -v -H "Content-Type: application/json" -X POST -d 'json_string' http://localhost:3000/api/v1/subusers
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License