【PHP】file_get_contentsでユーザーエージェントを指定する

この記事について

環境PHP
目的file_get_contentsでユーザーエージェントを指定する
結果stream_context_createでheaderにUser-Agentを設定して第3引数に渡す

つまずきポイント要約

  • 指定しなければUserAgentは「PHP/x.x.x」になる

file_get_contentsでユーザーエージェントを指定する方法のおぼえ書き。
ユーザーエージェントで表示内容を振り分けるページに有効。

//この設定がなければ、UserAgentは「PHP/x.x.x」になる。

$context = stream_context_create(array('http' => array(
'method' => 'GET',
'header' => 'User-Agent: Mozilla/6.4 (compatible; MSIE 4.0; Windows 98; DigExt)',
)));
file_get_contents($url, false,$context);

参考ページ:こちら

タイトルとURLをコピーしました