简体   繁体   中英

PHP curl get header parameters

I'm using curl with PHP for getting the header response of an API call.

This is my code:

$curl = curl_init();

curl_setopt($curl, CURLOPT_URL,            'http://localapi.com/v1/users');
curl_setopt($curl, CURLOPT_HEADER,         true);
curl_setopt($curl, CURLOPT_NOBODY,         true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_TIMEOUT,        10);
curl_setopt($curl, CURLOPT_HTTPHEADER,     array("authorization: Basic dmt5MVVTeXg3ZXpKYXVEZGtta2phZThfQ0tXa2tTQkY6"));
$response = curl_exec($curl);

The $response returna the header:

HTTP/1.1 200 OK Date: Wed, 15 Jun 2016 13:48:43 GMT Server: Apache/2.4.18 (Unix) PHP/5.5.31 X-Powered-By: PHP/5.5.31 X-Rate-Limit-Limit: 1 X-Rate-Limit-Remaining: 0 X-Rate-Limit-Reset: 0 X-Pagination-Total-Count: 1 X-Pagination-Page-Count: 1 X-Pagination-Current-Page: 1 X-Pagination-Per-Page: 20 Link: ; rel=self Content-Type: application/json; charset=UTF-8 1

Is there a method for access to the single header variables like an array?

Thanks in advance for the help.

You can assign a callback for Curl to process the headers in the response using CURLOPT_HEADERFUNCTION . By providing the $headers variable for the callback to assign the results, you can access them as an array after curl_exec has finished.

$headers = [];

curl_setopt($curl, CURLOPT_HEADERFUNCTION, function ($ch, $header) use (&$headers) {
    $matches = array();

    if ( preg_match('/^([^:]+)\s*:\s*([^\x0D\x0A]*)\x0D?\x0A?$/', $header, $matches) )
    {
        $headers[$matches[1]][] = $matches[2];
    }

    return strlen($header);
});

curl_exec($curl);

$headers will now contain an associative array of the response headers

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM