動かざることバグの如し

近づきたいよ 君の理想に

コピペで使えるcurlでHTTPリクエストする.php

使用頻度高いのでテンプレートってことでメモ

確認環境

コード

<?php
// GETパラメータ
$params = [
  'key' => 'value'
];
$url = 'https://httpbin.org/get?' . http_build_query($params);
// $url = 'https://httpbin.org/status/500';
$curl = curl_init();
$curl_options = [
  CURLOPT_URL => $url,
  // データを取得できるように
  CURLOPT_RETURNTRANSFER => true,
  // リダイレクト許可
  CURLOPT_FOLLOWLOCATION => true,
  // status_code > 400の場合エラーに
  CURLOPT_FAILONERROR => true
];
curl_setopt_array($curl, $curl_options);
$response = curl_exec($curl);
$info = curl_getinfo($curl);

if (curl_errno($curl)) {
  $error = curl_error($curl);
  echo $error;
}
curl_close($curl);

if(!isset($error)) {
  $json = json_decode($response);
  var_export($json);
}

エラーの場合、$errorにエラーメッセージがセットされる。

詳しいレスポンス情報を見たい

curl_close() する前に curl_getinfo() すると詳細を取得できる。

<?php
$info = curl_getinfo($curl);
var_export($info);

すると以下のようなデータを取得できる

array (
  'url' => 'https://httpbin.org/status/500?key=value',
  'content_type' => NULL,
  'http_code' => 500,
  'header_size' => 0,
  'request_size' => 68,
  'filetime' => -1,
  'ssl_verify_result' => 0,
  'redirect_count' => 0,
  'total_time' => 0.705413,
  'namelookup_time' => 0.001785,
  'connect_time' => 0.175847,
  'pretransfer_time' => 0.518781,
  'size_upload' => 0.0,
  'size_download' => 0.0,
  'speed_download' => 0.0,
  'speed_upload' => 0.0,
  'download_content_length' => -1.0,
  'upload_content_length' => -1.0,
  'starttransfer_time' => 0.705382,
  'redirect_time' => 0.0,
  'redirect_url' => '',
  'primary_ip' => '3.220.112.94',
  'certinfo' => 
  array (
  ),
  'primary_port' => 443,
  'local_ip' => '172.17.0.3',
  'local_port' => 45232,
  'http_version' => 3,
  'protocol' => 2,
  'ssl_verifyresult' => 0,
  'scheme' => 'HTTPS',
  'appconnect_time_us' => 518414,
  'connect_time_us' => 175847,
  'namelookup_time_us' => 1785,
  'pretransfer_time_us' => 518781,
  'redirect_time_us' => 0,
  'starttransfer_time_us' => 705382,
  'total_time_us' => 705413,
)