[PHP] Cookieの取得
スポンサーリンク
stream_context_create()とfile_get_contents()でhtmlを取得した際にCookieを取り出す方法のメモ。
$headers = array(
'User-Agent: Mozilla/5.0',
'Content-Type: application/x-www-form-urlencoded'
);
$options = array('http' => array(
'method' => 'GET',
'header' => implode("\r\n", $headers),
));
$content = file_get_contents("http://foobar.com" ,false ,stream_context_create($options ) );
foreach ($http_response_header as $val) {
if ( preg_match("/Set-Cookie:(.*)/u", $val, $match) ) {
$cookies[] = $match[1];
}
}
httpラッパーを使うと定義済み変数の$http_response_headerにHTTPレスポンスヘッダが代入されるので、ここからCOOKIEを取り出す。$http_response_headerは配列で、COOKIEは“Set-Cookie:”から始まる文字列の後にあるのでそれを正規表現で取得する。2行以上に渡る場合もあるので全て取得する。
スポンサーリンク