Posted at

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

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

ダウンロード

git clone git://github.com/rmccue/Requests.git


http_post.php

#! /usr/bin/php

<?php
// ------------------------------------------------------------------
// http_post.php
//
// Oct/10/2018
//
// ------------------------------------------------------------------
include('Requests/library/Requests.php');

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

Requests::register_autoloader();

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

$request = Requests::post($url, array(), $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: 153.233.132.240
url: http://httpbin.org/post
*** 終了 ***