2011-12-23 59 views
0

我有从服务器发送以下响应。如何将字符串www-authenticate的部分提取到名为$ realm,$ nonce,$ opaque的变量中?如何在变量中使用http头响应值?

正在由卷曲请求产生以下输出和即时打印响应头:

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 

回答

1

首先,解析报头到通用阵列:

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

然后,解析WWW-Authenticate标头有这样的东西:

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

此简短代码在多行标题值方面存在问题。请注意,RFC是在这里:[rfc2616 4.2 Message Headers](http://tools.ietf.org/html/rfc2616#section-4.2) – hakre 2012-08-04 20:38:36

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

这得到头与getallheaders()可以,拿起您的www-auth的,然后过滤引号之间的每一个值到$用正则表达式匹配阵列。通过$ matches [0]等访问您的值。