2

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.

1 Answer 1

5
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, 'http://www.google.com/');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER,true);

$result = curl_exec($ch);

curl_close($ch);

list($headers, $content) = explode("\r\n\r\n",$result,2);

// Print header
foreach (explode("\r\n",$headers) as $hdr)
    printf('<p>Header: %s</p>', $hdr);

// Print Content
echo $content;
Sign up to request clarification or add additional context in comments.

3 Comments

What if \r\n\r\n appears in the body?
This has a few possible pitfalls if used on the wider internet: some servers will not use /r/n line endings, sometimes your request will be in response to a 100-continue request and have multiple header sections etc
Even thought this works, it should be considered vulnerable!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.