在发布请求后,我想从最后两个set-cookie标头中获取sid的值。
sid=20076232_f83094c0b2cd89e6e2ee92cdc23eb36c;
是我所需要的。
function SendRequest($url, $method, $data, $headers) {
$context = stream_context_create(array
(
'http' => array(
'method' => $method,
'header' => $headers,
//'content' => http_build_query($data)
'content' => $data
)
));
$response_body = file_get_contents($url, false, $context);
//var_dump($http_response_header);
return array(
'headers' => $http_response_header,
'body' => $response_body
);
}
get_headers()
函数返回一个数组,但无法通过索引号访问它。有时候是随机的
响应头看起来像这样
HostName: *.*.2.111
Set-Cookie: nickname=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT; Max-Age=0; path=/;
Set-Cookie: sid=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT; Max-Age=0; path=/;
Set-Cookie: nickname=%25E4%25B8%2580%25E8%2591%2589%25E9%2580%2599%25E5%25A4%25A9; expires=Mon, 22-Oct-2018 13:44:14 GMT; Max-Age=2592000; path=/
Set-Cookie: sid=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT; Max-Age=0; path=/
Set-Cookie: sid=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT; Max-Age=0; path=/;
Set-Cookie: nickname=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT; Max-Age=0; path=/;
Set-Cookie: nickname=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT; Max-Age=0; path=/
Set-Cookie: sid=20076232_f83094c0b2cd89e6e2ee92cdc23eb36c; expires=Mon, 22-Oct-2018 13:44:14 GMT; Max-Age=2592000; path=/
Transfer-Encoding: chunked
X-Powered-By: PHP/5.5.38-pl0-gentoo
答案 0 :(得分:0)
您可以使用get_headers
来过滤preg_grep
的输出:
# ↓↓ hex ↓↓
$sids = preg_grep("/sid=([\d_a-f]+);/", $headers);
然后使用preg_match
提取最后一个有效ID。或者只是将标头内嵌到一个文本Blob中,然后提取第一个匹配项(看到只有一个匹配项)。