YD8877
YD8877

Reputation: 10800

How to take http header response values in a variable?

I have the following response being sent from a server. How do i extract the part of the string www-authenticate into variable called $realm, $nonce, $opaque ?

The following output is being generated by a curl request and i'm printing the response headers :

HTTP/1.1 401 Unauthorized
Cache-Control: private
Date: Fri, 23 Dec 2011 05:49:41 GMT
Content-Length: 0
Content-Type: text/html
WWW-Authenticate: Digest realm="[email protected]", nonce="3133323436313933383137343820335916269c13227f30b07bd83a1c7e0d", opaque="6e6f742075736564"
RETS-Version: RETS/1.5
X-Powered-By: Servlet/2.5 JSP/2.1

Upvotes: 0

Views: 696

Answers (3)

kontur
kontur

Reputation: 5217

$headers = getallheaders();
preg_match_all('/\"([^"])*\"/', $headers['WWW-Authenticate'], $matches);
print_r($matches);

This gets the headers with getallheaders(), picks your www-auth, and then filters every value between quotes into the $matches array by a regular expression. Access your values via $matches[0] etc.

Upvotes: 0

josegil
josegil

Reputation: 365

Using the function get_headers http://es2.php.net/get_headers you can get an array with the values of the header.

Upvotes: 0

deceze
deceze

Reputation: 522513

First, parse the headers into a general array:

$headers = explode("\n", $headers);
foreach ($headers as $header) {
    list($key, $value) = explode(': ', $header, 2);
    $headers[$key] = $value;
}

Then, parse the WWW-Authenticate header with something like this:

$params = array();
preg_match_all('/(\w+)="([^"]+)"/', $headers['WWW-Authenticate'], $matches, PREG_SET_ORDER);
foreach ($matches as $match) {
    $params[$match[1]] = $match[2];
}

Upvotes: 1

Related Questions