概要
PHPも様々なライブラリがある。
サーバ側は、通常のPHPでも可能。
クライアント側は、pecl::HttpRequestやcURLなどを使う。
準備
ここではpecl::HttpRequestを使う。
pecl_httpのバージョンによっては実行時エラーが発生する。
1.7.6を使用することにする。
pecl_httpのインストール
yum install zlib-devel libcurl-devel pecl install pecl_http-1.7.6
php.ini または、/etc/php.d/にファイルを作成して http.soを有効にする
extension=http.so
PHP REST
サーバ
<?php header("Content-Type: text/plain"); // echo "hoge"; $args = array_merge($_GET, $_POST); echo $args["a"] + $args["b"]; ?>
クライアント(PHP標準の関数のみ使う場合)
<?php $url = 'http://localhost/~centos/test3.php'; $data = array ( 'a' => 5, 'b' => '4', ); $headers = array( 'Content-Type: application/x-www-form-urlencoded', ); $options = array( 'http' => array( 'method' => 'POST', 'content' => http_build_query($data), 'header' => implode("\r\n", $headers), ) ); $contents = file_get_contents($url, false, stream_context_create($options)); print_r($contents); ?>
クライアント(cURLを使う場合)
<?php $url = 'http://localhost/~centos/test3.php'; $data = array ( 'a' => 5, 'b' => '4', ); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); curl_setopt($ch, CURLOPT_HEADER, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $result = curl_exec($ch);
// エラーの場合はスロー $errorno = curl_errno($ch); $errormsg = curl_error($ch); if ($errorno !== 0) { throw new Exception($errormsg, $errorno); } print_r($contents); ?>
クライアント(pecl httpを使う場合)
<?php function get() { // $r = new HttpRequest('http://localhost:8080/add', HttpRequest::METH_GET); $r = new HttpRequest('http://localhost/~centos/test3.php', HttpRequest::METH_GET); $r->addQueryData(array('a' => 3, 'b' => 4)); try { $r->send(); if ($r->getResponseCode() == 200) { echo $r->getResponseBody()."\n"; } else { echo $r->getResponseCode()."\n"; } } catch (HttpException $ex) { echo $ex; } } function post() { // $r = new HttpRequest('http://localhost:8080/add/add2', HttpRequest::METH_POST); $r = new HttpRequest('http://localhost/~centos/test3.php', HttpRequest::METH_POST); $r->addPostFields(array('a' => '5', 'b' => '6')); try { $r->send(); if ($r->getResponseCode() == 200) { echo $r->getResponseBody()."\n"; } else { echo $r->getResponseCode()."\n"; } } catch (HttpException $ex) { echo $ex; } } get(); post(); ?>
[カテゴリ: プログラミング言語 > PHP]
[通知用URL]
Tweet
最終更新時間:2017年02月12日 21時20分41秒