file_get_contentsでのアクセス時にUserAgentを変更する方法

PHP

09:39:10, by admin Email , 92 words, 11931 views   Japanese (JP) del.icio.us

UserAgentのためにcurlやPEAR::HTTP_Requestを用意する必要はなさそうだ。

(ノ・・)ン。。。。。。(((●コロコロッ

$context = stream_context_create(array('http' => array(
'method' => 'GET',
'header' => 'User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)',
)));
$url = "http://hain.jp";
$data = file_get_contents($url, false, $context);


stream_context_createを使うのがポイント

[More:]


PHPは5以上。
file_get_contents、もっと言うとfopenにURLを指定してサイトにアクセスすると、
サイトのデータが文字列で取れるのはご存じだと思う。
ただ、その際送信されるユーザーエージェントは
PHP/x.x.x
これでも別段問題はないのだが、
ユーザーエージェントによって表示方法を動的に変えているサイトも珍しくはない。
特定のUserAgentの時のページを取得したい場合はcURL関数やPEAR::HTTPRequestなどを持ち出さなければならない。
それは少し面倒だ。

しかし、stream_content_createを用いることで、
パラメータを指定するだけでUAの情報を変更することが出来る。
これはメリットが大きいはず。
ユーザーエージェントのみならず、
HTTPヘッダはすべて変更が可能なので、
file_get_contentsでPOSTを送信することも出来る。



php.iniのuser_agentを変更することでも可能らしい。
これはPHP4でも可。
ini_set('user_agent', 'User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)');



stream_context_createのオプションとして利用できるhttpパラメータは以下に記載されている。
http://www.php.net/manual/en/wrappers.http.php#id3886679
これによると、timeout時間やprotocolのバージョンも制御できる。

Trackback address for this post:

http://hain.jp/htsrv/trackback.php/172

Comments, Trackbacks:

No Comments/Trackbacks for this post yet...

Leave a comment:

Your email address will not be displayed on this site.
Your URL will be displayed.

Allowed XHTML tags: <p, ul, ol, li, dl, dt, dd, address, blockquote, ins, del, span, bdo, br, em, strong, dfn, code, samp, kdb, var, cite, abbr, acronym, q, sub, sup, tt, i, b, big, small>
(Line breaks become <br />)
(Set cookies for name, email and url)
(Allow users to contact you through a message form (your email will NOT be displayed.))
This is a captcha-picture. It is used to prevent mass-access by robots.

Please enter the characters from the image above. (case insensitive)

powered by b2evolution

shinobi

Neighbors
Relative
Favorites
PR

極論istの技術屋を始めて早幾年。 流れの速い業界の波にもまれながらも精一杯生きている様をとくとごらんあれ。

Archives
スポンサー

Latest bookmark
Search

Categories

Who's Online?
Misc
Syndicate this blog XML

Valid XHTML 1.0! Valid CSS! Valid RSS 2.0! Valid Atom 1.0!