HTTP_Request2を使ってファイルを送信する
自前でsocket通信を書くのはしんどいのでpearのHTTP_Request2を使って通信を行う、とりあえずHTTP_Request2をインストールする~
あまり環境を変更したくないので今回はpyrusを使ってみる~
以下pyrusの設定~
pyrus の設定
1. http://pear2.php.net/から「pyrus」をダウンロードする
2. pearを設定するディレクトリにダウンロードした「pyrus.phar」をおく
3. 「/Users/box406/Sites/myproject/」に「pyrus.phar」を設置
4. 「vender」ディレクトリを作成
$ mkdir /Users/box406/Sites/myproject/vender
5.「vender/bin」ディレクトリを作成
$ mkdir /Users/box406/Sites/myproject/vender/bin
6. pyrus の設定
$ php pyrus.phar mypear /Users/box406/Sites/myproject/vender $ php pyrus.phar set bin_dir /Users/box406/Sites/myproject/vender/bin
7. インストール
$ php pyrus.phar install pear/HTTP_Request2-2.1.1
HTTP_Request2を使ってファイルを送信する
以下サンプルソース
<?php // ini set ini_set('include_path', dirname(__FILE__) . "/vender/php/" . ini_get("include_path")); // require require_once "HTTP/Request2.php"; // init $post_filename = "20121225205707.pdf"; $post_url = "http://hogehoge.com/get.php"; $finfo = finfo_open(FILEINFO_MIME_TYPE); $file_content_type = ""; // get file content type $file_content_type = finfo_file($finfo, $post_filename); finfo_close($finfo); // send $request = new HTTP_Request2($post_url); $request->setMethod(HTTP_Request2::METHOD_POST) ->addPostParameter("username", "hogefuga") ->addUpload("convert_file", $post_filename, $post_filename, $file_content_type); $responce = $request->send()->getBody(); echo $responce;
順番に説明を書きます
1. ローカル環境の諸事情と時間の制限があったのでとりあえず「include_path」を設定してpyrusで設定したpearの方に無理矢理向ける
// ini set ini_set('include_path', dirname(__FILE__) . "/vender/php/" . ini_get("include_path"));
2. HTTP_Request2の読込み、本当はautoloadとか素敵な機能を使うべきですが諸事情の為、手動での読込み
// require require_once "HTTP/Request2.php";
3. 初期化
// init $post_filename = "20121225205707.pdf"; $post_url = "http://hogehoge.com/get.php";
使う変数に初期値を与える
$finfo = finfo_open(FILEINFO_MIME_TYPE); $file_content_type = "";
ファイルをアップロード時に「content type」の指定があるので用意
4. アップロードするファイルのcontent typeを取得する
// get file content type $file_content_type = finfo_file($finfo, $post_filename); finfo_close($finfo);
忘れずにcloseする~
「finfo_file()」はphp5.3から組み込まれたらしい、詳しくは以下を参照~
php manual finfo_file
しかし「finfo_file」って名前はどうにかならんかったのかな〜~
5. オブジェクトを生成
$request = new HTTP_Request2($post_url);
6. HTTP メソッドを設定
$request->setMethod(HTTP_Request2::METHOD_POST)
※POSTで送信する場合は「HTTP_Request2::METHOD_POST」
※GETで送信する場合は「HTTP_Request2::METHOD_GET」
7. 送信するパラメーターを設定
->addPostParameter("username", "hogefuga")
複数送信する場合は連想配列で指定する
->addPostParameter(array("username" => "hogefuga", "mail" => "hogefuga@gmail.com"))
8. 送信するファイルを設定
->addUpload("convert_file", $post_filename, $post_filename, $file_content_type);
第1引数 = フィールドの名前、ファイルを受け取る際に指定する名前 (※$_FILES["convert_file"])
第2引数 = アップロードするファイルのパス
第3引数 = 送信されるファイルの名前
第4引数 = ファイルのコンテンツタイプ(※finfo_fileで取得した内容)
9. 送信する、返された値を取得
$responce = $request->send()->getBody();
10. 画面に表示
echo $responce;
以上です
簡単なサンプルで理解できていないところもありますが、許して下さい