PHP POSTリクエスト送信方法|基本とサンプルコード
PHPでPOSTリクエストを送信する際には、curlまたはfile_get_contents関数を使用できます。
curlを使用してPOSTリクエストを送信する例は以下の通りです。
$url = 'http://example.com/post_endpoint';
$data = array('key1' => 'value1', 'key2' => 'value2');
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
if(curl_errno($ch)){
echo 'Curl error: ' . curl_error($ch);
}
curl_close($ch);
echo $response;
file_get_contentsを使用してPOSTリクエストを送信する例を以下に示します:
$url = 'http://example.com/post_endpoint';
$data = array('key1' => 'value1', 'key2' => 'value2');
$options = array(
'http' => array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);
echo $response;
以上のコード例では、$url変数がターゲットのURLアドレスであり、$data変数がPOSTリクエストのデータである。curl関数またはfile_get_contents関数を使用してデータをターゲットURLに送信し、返ってきたデータを取得します。