3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【PHP】cURL関数でPOSTする方法(送信&受け取る(API))

Posted at

送信側

curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_params);

この2行でPOSTできるようにする。

送りたい値を連想配列にしたのち、json_encodeでJSON形式にして送る

  $base_url = 'api.php';
  $params = [
    'user_id'  => $user_id,
    'password' => $password
  ];
  $json_params = json_encode($params);

  $headers = [
    'Content-Type: application/json',
    'Accept-Charset: UTF-8',
  ];

  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $base_url);
  curl_setopt($ch, CURLOPT_POST, TRUE);
  curl_setopt($ch, CURLOPT_POSTFIELDS, $json_params);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  $login_info_return_value = curl_exec($ch);
  curl_close($ch);

###受け取るAPI側

JSONで受け取る

$user_id  = filter_input(INPUT_POST, 'user_id');
$password = filter_input(INPUT_POST, 'password');

$post_json_data = file_get_contents("php://input");
// JSONファイルを連想配列へ変換
$post_obj_data = json_decode($post_json_data, true);

php://input php://input は読み込み専用のストリームで、 リクエストの body 部から生のデータを読み込むことができます。 php://input は、 enctype=”multipart/form-data” に対しては使用できません。 https://www.php.net/manual/ja/wrappers.php.php

  • $post_json_data にJSON形式で格納される
  • それを連想配列に戻して使用する
3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?