Is It Possible For PHP Curl To Retrieve Both Response Headers And Body In A Single Request?

Yes, PHP cURL can retrieve both response headers and body in a single request. You can use the CURLOPT_HEADER option to include the response headers in the returned output and the CURLOPT_RETURNTRANSFER option to return the response body as a string.

Here’s an example:

$url = 'http://example.com/api';

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);

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

curl_close($ch);

echo "Response Headers: \n" . $header . "\n";
echo "Response Body: \n" . $body;

In this example, the CURLOPT_HEADER option is set to true to include the response headers along with the body in the returned output from curl_exec(). The header size is obtained using curl_getinfo() and used to separate the headers and body portions from the combined response.

You can then echo the header and body separately as needed.

About the Author Rex

I'm a passionate tech blogger with an insatiable love for programming! From my early days tinkering with code, I've delved into web dev, mobile apps, and AI. Sharing insights and tutorials with the world is my joy, connecting me to a global community of like-minded tech enthusiasts. Python holds a special place in my heart, but I embrace all challenges. Constantly learning, I attend tech conferences, contribute to open-source projects, and engage in code review sessions. My ultimate goal is to inspire the next generation of developers and contribute positively to the ever-evolving tech landscape. Let's code together!