end0tknr's kipple - web写経開発

太宰府天満宮の狛犬って、妙にカワイイ

cross domainなjsonpでは、postが使用できない為、php + curlで proxy ? を作成

以下のような感じかと思います

<?php

const REMOTE_API = "http://192.168.63.3/cgi-bin2/form.php";

main();


function main(){
    my_ini_set();

    $getdata  = $_GET;
    $postdata = $_POST;
    $referer  = $_SERVER['HTTP_REFERER'];

    $response = post_to_remote_url($getdata,$postdata,$referer);

    http_response_code( $response["head"]["http_code"] );
    header("Content-Type: ". $response["head"]["content_type"]);
    echo $response["body"];
}


function my_ini_set(){  // php.ini への直接登録でなく、こちらで設定
    ini_set("log_errors",     "On" );
    ini_set("error_reporting","E_ALL");
    
    ini_set("date.timezone","Asia/Tokyo");
    
    mb_language('Japanese');
    mb_internal_encoding('UTF-8');
}

function post_to_remote_url($getdata,$postdata,$referer){

    $url = REMOTE_API;
    if( count($getdata) ){
        $url .= "?" . http_build_query($getdata);
    }

    $ch = curl_init();
    
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_TIMEOUT,10);

    curl_setopt($ch, CURLOPT_REFERER, $referer);
    curl_setopt($ch, CURLOPT_URL,     $url);
    curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($postdata));
    
    // 証明書の検証なし
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false);
    // curl_exec()の返値を文字列で出力
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
    // 以下をtrueとすると、http_status≧400以上で error
    curl_setopt($ch, CURLOPT_FAILONERROR,   false);
    
    $ret_vals = [];
    $ret_vals["head"] = curl_getinfo($ch);
    $ret_vals["body"] = curl_exec($ch);
    
    curl_close($ch);

    return $ret_vals;
}