Categories
PHP

PHP cURL retrieve response headers AND body in a single request

$url = "https://www.googleapis.com";
$ch = curl_init();
$headers = [];
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

$body = curl_exec($ch);

// this function is called by curl for each header received
curl_setopt(
    $ch,
    CURLOPT_HEADERFUNCTION,
    function ($curl, $header) use (&$headers) {
        $len = strlen($header);
        $header = explode(':', $header, 2);
        if (count($header) < 2) { // ignore invalid headers
            return $len;
        }

        $headers[strtolower(trim($header[0]))][] = trim($header[1]);

        return $len;
    }
);

$data = curl_exec($ch);
print_r($headers);
print_r($body);

Ref: https://stackoverflow.com/questions/9183178/can-php-curl-retrieve-response-headers-and-body-in-a-single-request

Leave a Reply