ユーザーエージェント文字列の変更- 偽装ともいう

HTTPクライアントのユーザーエージェント文字列を変更する方法のメモ。

wget

-U または --user-agent で可。

wget -U "Mozilla/5.0" http://www.example.com/

ヘルプの記述

  -U,  --user-agent=AGENT      User-Agent として Wget/VERSION ではなく AGENT を使う

lynx

-useragent で可。

lynx -useragent="Mozilla/5.0"

ヘルプの記述

  -useragent=Name   set alternate Lynx User-Agent header

ヘルプでは=でつないでいるが、スペースでも動いた。

lynx -useragent "Mozilla/5.0"

文字列にLynxまたはL_y_n_xが含まれていないと警告が出る。

注意:  User-Agent に "Lynx" あるいは "L_y_n_x" という文字列が含まれていません!
Warning: User-Agent string does not contain "Lynx" or "L_y_n_x"!

curl

-A または --user-agent で可。

curl -A "Mozilla/5.0" http://www.example.com/

ヘルプの記述

 -A/--user-agent <string> User-Agent to send to server (H)

PHP PEAR::HTTP_Request

HTTP_Request::addHeader()で可

require_once "HTTP/Request.php";
$req = new HTTP_Request('https://www.example.com/');
$req->addHeader('User-Agent','Mozilla/5.0');
$req->sendRequest();

デフォルト値は 「PEAR HTTP_Request class ( http://pear.php.net/ )」

HTTP_Request::addHeader()

PHP PEAR::HTTP_Client

HTTP_Client::setDefaultHeader()で可。

require_once "HTTP/Client.php";
$client = new HTTP_Client();
$client->setDefaultHeader('User-Agent', 'Mozilla/5.0');
$client->get('http://www.example.com/');

こちらもデフォルト値は「PEAR HTTP_Request class ( http://pear.php.net/ )」であり
内部でHTTP_Requestを使っている。

HTTP_Client::setDefaultHeader()


PHP file_get_contents

ストリームコンテキストで設定できる。

$opts = array('http' =>
  array(
    'header' => "User-Agent: Mozilla/5.0\r\n"
  )
);
$context = stream_context_create($opts);
file_get_contents('http://www.example.com/', false, $context);

※file_get_contentsならびにstream_contenxt_createが利用できるのはPHP4.3.0以降。

PHP curl

curl_setopt で設定できる。

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/');
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla...');
curl_exec($ch);
curl_close($ch);

http://php.net/manual/ja/function.curl-setopt.php

Google Chrome

起動時に --user-agent で変更可。

"C:\Program Files\Google\Chrome\Application\chrome.exe" --user-agent="Mozilla/5.0"


ユーザエージェント