エントリー

file_get_contents()でgetリクエストとpostリクエストを送るメモ

PHPの file_get_contents() を使えばファイルの内容を表示できますが、指定したサーバーにgetやpostのリクエストを送ることもできます。

WebAPIを扱うときなど、たまに過去のコードを探すので自分用にメモ。

get

<?php

$result = file_get_contents('http://www.example.com/get.php?test1=test1&test2=テスト2');
echo '<pre>' . $result . '</pre>';

?>

http://www.example.com/get.php に対して test1=test1test2=テスト2 をgetで送信し、結果を画面に表示。

post

<?php

$result = file_get_contents(
  'http://www.example.com/post.php',
  false,
  stream_context_create(
    array(
      'http' => array(
        'method' => 'POST',
        'header' => implode(
          "\r\n",
          array(
            'Content-Type: application/x-www-form-urlencoded'
          )
        ),
        'content' => http_build_query(
          array(
            'test1' => 'test1',
            'test2' => 'テスト2'
          )
        )
      )
    )
  )
);
echo '<pre>' . $result . '</pre>';

?>

http://www.example.com/post.php に対して test1=test1test2=テスト2 をpostで送信し、結果を画面に表示。

ページ移動

ユーティリティ

カテゴリー

検索

エントリー検索フォーム
キーワード

過去ログ

過去ログ表示フォーム
キーワード

Feed