John Davidson

PHP cURL: Read a specific response header

0 comments
Message:


I am using cURL in PHP to POST to an endpoint that is creating a resource. It returns a 201 response with a Location header giving the URL of the resource created. I also get some information in the body of the response.



What's the best way to get the plain-text body of the response, and also get the value of the location header? curl_getinfo doesn't return that header, and when I do this:



    curl_setopt($ch, CURLOPT_HEADERFUNCTION, function($ch, $header) {
var_dump($header);
});


I only see one header dumped out--the "HTTP/1.1 201 Created" response code.



My Answer:
To read a specific response header in PHP cURL, you can use the `CURLOPT_HEADER` option to include the headers in the response. Here's an example of how you can do this:

php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://example.com/api/resource');
curl_setopt($ch, CURLOPT_POST, 1);
// Add your POST data here if needed
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);

$response = curl_exec($ch);

$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$header = substr($response, 0, $header_size);
$body = substr($response, $header_size);

// Parse the headers to get the Location header
$headers = explode("\r\n", $header);
$location = '';
foreach ($headers as $h) {
if (strpos($h, 'Location:') === 0) {
$location = trim(substr($h, 9));
break;
}
}

// Output the body and location header
echo "Body: $body\n";
echo "Location: $location\n";

curl_close($ch);


In this code snippet, we set the `CURLOPT_HEADER` option to true to include the headers in the response. We then use `curl_getinfo` to get the size of the headers and split the response into the headers and body. We then parse the headers to find the Location header and output both the body and the Location header.

This should allow you to read the plain-text body of the response and get the value of the Location header.

Rate this post

4 of 5 based on 7830 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us