LoginSignup
0
0

PHP の http クライアントの使い方 (Post)

Last updated at Posted at 2018-10-10

Requests というライブラリーを使います。

ライブラリーのインストール

composer require rmccue/requests
http_post.php
#! /usr/bin/php
<?php
// ------------------------------------------------------------------
//  http_post.php
//
//					Jul/31/2023
//
// ------------------------------------------------------------------
require_once 'vendor/rmccue/requests/src/Autoload.php';
WpOrg\Requests\Autoload::register();

fputs (STDERR,"*** 開始 ***\n");

Requests::register_autoloader();

$url = 'https://httpbin.org/post';
$args = array('user' => 'jiro','password' => '123456');

$request = WpOrg\Requests\Requests::post($url, array('Accept' => 'application/json'), $args);

// var_dump($request->body);

var_dump($request->status_code);

$json_string = $request->body;
$data_aa = json_decode ($json_string,true);
print("-----------\n");
var_dump($data_aa["form"]);

print("Host:\t" . $data_aa["headers"]["Host"] . "\n");
print("origin:\t" . $data_aa["origin"] . "\n");
print("url:\t" . $data_aa["url"] . "\n");
fputs (STDERR,"*** 終了 ***\n");

// ------------------------------------------------------------------
?>

実行結果

$ ./http_post.php 

int(200)
-----------
array(2) {
  ["password"]=>
  string(6) "123456"
  ["user"]=>
  string(4) "jiro"
}
Host:	httpbin.org
origin:	219.126.139.113
url:	https://httpbin.org/post
*** 終了 ***

次のバージョンで確認しました。

$ php --version
PHP 8.2.8 (cli) (built: Jul  5 2023 18:47:24) (NTS)
Copyright (c) The PHP Group
Zend Engine v4.2.8, Copyright (c) Zend Technologies
0
0
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
0
0