【PHP】サーバ間通信に意外に使える関数

PHPでサーバ間通信を言えば、fsockやcurlを使うイメージですが、やや複雑な感じをしていました。
最近になって、ファイル内容の取得に多用している関数「file_get_contents」でもサーバ間通信で結構使えることを知りました。
基本用法
1 2 3 4 5 6 7 8 9 10 11 | <?php $url = 'http://www.example.net/hoge.php'; $data = array( 'parma1' => 'aaa', 'parma2' => 'bbb', ); $options = array('http' => array( 'method' => 'POST',// POSTでも使える! 'content' => http_build_query($data), )); $contents = file_get_contents($url, false, stream_context_create($options)); |
ヘッダを追加
ユーザーエージェントを指定したいやBasic認証情報を追加したい場合に使えます。
1 2 3 4 5 6 7 8 9 10 11 12 | <?php //... $headers = array( 'User-Agent: My User Agent 1.0', 'Authorization: Basic '.base64_encode('user:pass'), ); $options = array('http' => array( 'method' => 'POST', 'content' => http_build_query($data), 'header' => implode("\r\n", $headers), )); //... |
最後に
使い慣れた関数を手軽く使えるのは嬉しいです。
「file_get_contents」の返り値が配列だと思いましたが、PHPのマニュアルを見たら、文字列ですので、どうぞご注意を。
Author Profile

スターフィールド編集部
SHARE