LoginSignup
8
7

More than 5 years have passed since last update.

phpからwgetでPOST

Last updated at Posted at 2012-03-06

とてもニッチなので必要になる人がいるかわからないネタです。
サーバの都合で、外部サーバとの連携がwgetでしかできないという事がありました。
誰かの役に立てばいいけど。。

<?php
    //POSTされたデータと、$_FILES['filedata']のデータ(jpgを想定)を
    //wgetで他のサーバにPOSTするサンプル
    //※fileの細かいチェックとか、判別とかは省いています。

    $post_target = "https://example.com/hoge.api"

    $postData = "";
    $postFile = "";
    $boundary = "-----=".md5(uniqid(rand()));

    //text data
    foreach( $_POST as $key => $value ){
        $postData .= "--{$boundary}\r\n";
        $postData .= "Content-Disposition: form-data; name='" . escapeshellcmd($key) . "'\r\n\r\n";
        $postData .= escapeshellcmd($value) . "\r\n";
    }

    //image data
    if($_FILES['filedata'] && $_FILES['filedata']['error'] === 0){
        $postData .= "--{$boundary}\r\n";
        $postData .= "Content-Disposition: form-data; name='filedata'; filename='hoge.jpg'\r\n";
        $postData .= "Content-Type: image/jpeg\r\n\r\n";
        $postData .= file_get_contents($_FILES['filedata']['tmp_name'])."\r\n";
    }

    if($postData != ""){
        $postData = $postData . '--' . $boundary . '--';

        //POSTでバイナリを送る場合は、multipart/form-data形式のファイルを作って
        //--post-fileオプションを使わないと送信出来ないみたい。
        $postFile = "tmp/".md5(uniqid(rand())).".data";
        $fp = fopen($postFile, "w");
        fwrite( $fp, $postData, strlen($postData));
        fclose($fp);

        $postData = '--header="Content-Type: multipart/form-data; boundary=' . $boundary . '" --post-file="' . $postFile . '" ';
    }


    //sslだった場合、--no-check-certificateオプションをつけないとエラーうまく送信できない。
    //※セキュリティー的に、この処置は暫定的であるべき。
    $https = "";
    if(strpos($post_target, "https://") !== false) $https = "--no-check-certificate ";


    //返りがxmlを想定。一度ファイルに保存する場合は"-O hote.xml"などにする。
    //passthru以外にもexecやsystemが使えるが、
    //返りがバイナリの場合、passthruでないと復元が面倒。
    //ただ、passthruは即出力してしまうので、事前にContent-typeを適宜設定しておかないとうまく動かない。
    //ob_startなどでバッファリングしたデータをチェックすればうまく処理できるかも。
    header('Content-type: text/xml; charset="UTF-8"');
    passthru("wget -O - " . $https . $postData . escapeshellcmd($post_target));

    //ゴミ掃除
    if($postFile && file_exists($postFile)) unlink($postFile);

8
7
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
8
7