Thursday, 21 August 2014

Reading the response message from a PUT request using PHP and cURL

Previously I’ve mentioned that I had to write some PHP to PUT some JSON data to a RESTful web API. After calling curl_exec() to make the PUT request I called curl_getInfo() to retrieve the HTTP status code from the response message, in order to output a success or failure message.

While debugging this function it was sometimes necessary to examine the request message being sent to the web API, to ensure its format was correct. This required setting some additional CURLOPT parameters, as shown in the code below.

1 function callRestAPI($uri, $signature, $json) {
2 $headers = array (
3 "Content-Type: application/json; charset=utf-8",
4 "Content-Length: " .strlen($json),
5 "X-Signature: " . $signature
6 );
7
8 $channel = curl_init($uri);
9 curl_setopt($channel, CURLOPT_RETURNTRANSFER, true);
10 curl_setopt($channel, CURLOPT_CUSTOMREQUEST, "PUT");
11 curl_setopt($channel, CURLOPT_HTTPHEADER, $headers);
12 curl_setopt($channel, CURLOPT_POSTFIELDS, $json);
13 curl_setopt($channel, CURLOPT_SSL_VERIFYPEER, false);
14 curl_setopt($channel, CURLOPT_CONNECTTIMEOUT, 10);
15 curl_setopt($channel, CURLOPT_VERBOSE, true);
16 curl_setopt($channel, CURLOPT_HEADER, true);
17 curl_setopt($channel, CURLINFO_HEADER_OUT, true);
18
19 $response = curl_exec($channel);
20 $request = curl_getInfo($channel, CURLINFO_HEADER_OUT);
21 $statusCode = curl_getInfo($channel, CURLINFO_HTTP_CODE);
22
23 echo $request . "<BR>";
24 echo $response . "<BR>";
25 echo $statusCode . "<BR>";
26
27 curl_close($channel);
28 return $statusCode;
29 }

 

 

 

 

The additions are to set:

  1. CURLOPT_VERBOSE to true in order to output verbose information.
  2. CURLOPT_HEADER to true to include the header in the output.
  3. CURLINFO_HEADER_OUT to true to track the request message.

Then, after executing the PUT request I called curl_getInfo to get information about the PUT request. Specifically I requested the request message string by  using the CURLINFO_HEADER_OUT constant. This provides the request message which can then be output for debugging purposes.

No comments:

Post a comment