PHP file_get_contentsでAPIサーバーにGET,POST,画像アップロード
FalconでAPIサーバーを作ってみました。Python + Falconで高速APIサーバーを作成する
APIサーバー Falcon post,headerの値の取得方法
PHPからこのAPIサーバーに接続してみます。
file_get_contentsで。
file_get_contentsでget
getリクエストを送信してみます。
APIサーバー側はこんな感じ。
- # -*- coding:utf-8 -*-
- import json
- import falcon
- class HelloResource(object):
- # getされた時の動作
- def on_get(self, req, res):
- msg = {
- "message": "Welcome to the Falcon"
- }
- res.body = json.dumps(msg)
- app = falcon.API()
- app.add_route("/", HelloResource())
- if __name__ == "__main__":
- from wsgiref import simple_server
- httpd = simple_server.make_server("0.0.0.0", 8000, app)
- httpd.serve_forever()
取得するPHP側。
- <?php
- // file_get_contentsでデータを取得
- $url = 'http://192.168.1.102:8000';
- $raw_data = file_get_contents($url);
- // jsonからstdClassに変換
- $data = json_decode($raw_data);
- // 結果を表示
- echo $data->message . PHP_EOL;
実行結果
# php sample.php
Welcome to the Falcon
ここまでは問題なし。
file_get_contentsでpost
データをpostしてみます。
サーバー側はこんな感じです。
- # -*- coding:utf-8 -*-
- import json
- import falcon
- class HelloResource(object):
- # postされた時の動作
- def on_post(self, req, res):
- # postパラメーターを取得
- body = req.stream.read()
- data = json.loads(body)
- # パラメーターの取得
- name = data['name']
- msg = {
- "message": "Hello, " + name
- }
- res.body = json.dumps(msg)
- app = falcon.API()
- app.add_route("/", HelloResource())
- if __name__ == "__main__":
- from wsgiref import simple_server
- httpd = simple_server.make_server("0.0.0.0", 8000, app)
- httpd.serve_forever()
PHP側、file_get_contentsでpostします。
- <?php
- // file_get_contentsでデータを取得
- $url = 'http://192.168.1.102:8000';
- // POSTするデータを作成
- $context = stream_context_create([
- 'http' => [
- 'method'=> 'POST',
- 'header'=> 'Content-type: application/json; charset=UTF-8',
- 'content' => json_encode(['name' => 'symfo'])
- ]
- ]);
- $raw_data = file_get_contents($url, false, $context);
- // jsonからstdClassに変換
- $data = json_decode($raw_data);
- // 結果を表示
- echo $data->message . PHP_EOL;
狙い通りの実行結果です。
# php sample.php
Hello, symfo
file_get_contentsで画像ファイルのpost
リクエストヘッダーにファイル名。
ボディーに画像のバイナリデータを要求するサンプルです。
- # -*- coding:utf-8 -*-
- import json
- import falcon
- class HelloResource(object):
- # postされた時の動作
- def on_post(self, req, res):
- # headerからファイル名を取得
- filename = req.get_header('File-Name')
- # bodyから画像ファイルのバイナリ取得
- body = req.stream.read()
- # ファイルを保存
- with open(filename, 'wb') as f:
- f.write(body)
- res.body = json.dumps({'message':'ok'})
- app = falcon.API()
- app.add_route("/", HelloResource())
- if __name__ == "__main__":
- from wsgiref import simple_server
- httpd = simple_server.make_server("0.0.0.0", 8000, app)
- httpd.serve_forever()
PHP側、ヘッダーにファイル名、ボディーに画像のバイナリデータを設定して送信します。
想定通り、サーバー側に「sample.jpg」というファイル名で画像ファイルが復元できました。
- <?php
- // file_get_contentsでデータを取得
- $url = 'http://192.168.1.102:8000';
- // 送信するデータ
- $filename = 'sample.jpg';
- $image = file_get_contents('cc2.jpg');
- // POSTするデータを作成
- $header = [
- "Content-Type: application/json; charset=UTF-8;",
- "Content-Length: ".strlen($image),
- "File-Name: " . $filename
- ];
- $context = stream_context_create([
- 'http' => [
- 'method'=> 'POST',
- 'header'=> implode("\r\n", $header),
- 'content' => $image
- ]
- ]);
- $raw_data = file_get_contents($url, false, $context);
- // jsonからstdClassに変換
- $data = json_decode($raw_data);
- // 結果を表示
- echo $data->message . PHP_EOL;
【参考URL】
file_get_contentsでPOSTデータ送信
PHP の file_get_contents は get どころか post も put も delete も upload もできる
- 関連記事
-
- CodeIgniter 3 + HTML5 FileAPI + jQueryで複数ファイルのアップロード
- CodeIgniter3 JSONを返すAPIサーバーとして使用する
- PHP file_get_contentsでAPIサーバーにGET,POST,画像アップロード
- PHP 配列の先頭の要素を取り出す(array_shift)
- ローカルストレージのファイルをComposerのリポジトリとして指定する
コメント