php proxy for jquery ajax cross site request

<?php

define('AUTO_LOGIN', true);
define('PLATFORM_URL', 'http://10.64.68.12:6543');


function socketRedirect()
{
    try 
    {
        if ( ! isset($_SERVER['PATH_INFO']) ) 
        {
            $response_code = 404;
            $header_status = sprintf("Status Code: %d", $response_code);
            header($header_status, true, $response_code);
            return;
        }

        $url = PLATFORM_URL . $_SERVER['PATH_INFO'];
        list($resp_code, $body) = JsonPost($url, GetRowPostData());
        
        $header_status = sprintf("Status Code: %d", $resp_code);
        header($header_status, true, $resp_code);        
        echo $body;
    }
    catch ( Exception $ex ) 
    {

        $response_code = 500;
        $header_status = sprintf("Status Code: %d", $response_code);
        header($header_status, true, $response_code);
    }    
}

function GetRowPostData()
{
    return file_get_contents('php://input');
}

/* POST JSON encoded version of $input to $url */
/* By Tim Hastings, http://www.nonhostile.com/howto-http-post-json-using-php.asp */
function JsonPost($url, $data) 
{
    list($notsused, $hostportres) = explode("://", $url, 2);
    list($hostport, $resource) = explode("/", $hostportres, 2);
    list($host, $port) = explode(":", $hostport, 2);
    $resource = '/' . $resource;
           
    $content_length = strlen($data);
    $requestMethod = $_SERVER["REQUEST_METHOD"];
    
    $fp = fsockopen($host, $port);
    fputs($fp, "$requestMethod $resource HTTP/1.1\r\n");
    fputs($fp, "Content-Type: application/json\r\n");
    fputs($fp, "Content-Length: $content_length\r\n");
    fputs($fp, "Connection: close\r\n\r\n");
    fputs($fp, $data, $content_length);

    $http_response = stream_get_contents($fp);
    fclose($fp);

    list($headers, $body) = explode("\r\n\r\n", $http_response, 2);
    
    $header_array = explode("\r\n", $headers);
    $http_response = $header_array[0];
    $resp_sections = explode(" ", $http_response);
    $resp_code = $resp_sections[1];
    
    return array($resp_code, $body);
}


function main() 
{    
    socketRedirect();
    return;
}

main();

?>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值