file_get_contentsでPOSTできる
意外と知られていませんが、PHPのfile_get_contents関数は、getだけじゃなくてpostもできます。
file_get_contentsは以下のようにstream_context_create関数を利用して送信時のパラメータを詳細に設定することができます。送信時のメソッドだけでなく、ユーザエージェントを変更する事も可能です。
$url = \'http://example.com/\';
$options = array(
\'http\' => array(
\'method\' => \'POST\',
\'content\' => http_build_query(
array(
\'q\' => \'ryus\',
)
),
\'header\' => implode(\"\\r\\n\",
array(
\'User-Agent: file_get_contents\'
)
),
));
$re = file_get_contents($url, false, stream_context_create($options));
var_dump($re);
?>
PHPでpostしようとするとPEARのHTTP_Requestを使う人も多いですが、単純なPOSTが必要になった時はfile_get_contentsの事も思い出してあげてください。
コメント (1)
こんな簡単にPOSTが出来たんですね^^;