PHP的Ajax跨域转发程序

Ajax有一个安全特性就是跨域访问的限制问题,虽然有很多解决的方法,但都没有使用代理的方式简单。

后来发现一个更简单的,就是给chrome浏览器添加 –allow-file-access-from-files –disable-web-security 启动参数,即可实现关闭安全检查的功能。

它的这个特性过份到访问同一个域下的不同端由都做了限制。有时候做测试开发很不方便。所以我就自己写了一个php的代理程序,由php接收ajax请求并转发到其他域的服务器,并将结果返回。

proxy.php代码如下:

<?php
error_reporting(0);

$destURL="http://otherdomain.com/to/path/script.jsp";

$queryString=$_SERVER['QUERY_STRING'];
if($_SERVER['REQUEST_METHOD']=='GET'){
    $url=$destURL.$queryString;
    echo file_get_contents($url);
}
else{
    $url=$destURL.$queryString;
    $context = array();
    $context['http'] = array(
        'method' => 'POST',
        'header'  => 'Content-type: application/x-www-form-urlencoded',
        'content' => http_build_query($_POST)
    );
    echo file_get_contents($url, false, stream_context_create($context));
}
?>

假设本来ajax想请求http://otherdomain.com/to/path/script.jsp这个脚本,但又不在同一个域上,这时把proxy.php放到脚本所在域,脚本通过请求proxy.php代理。

请求示例:

//var baseURL="http://otherdomain.com/to/path";
var baseURL="http://mydomain.com/proxy.php?";  //注意这个问号一定要带上。

//GET方式代理
xmlHttpRequest.open(“GET”,baseURL+"/script.jsp?a=1&b=2",true);

//POST方式代理可同时带get和post参数
xmlHttpRequest.open(“POST”,baseURL+"/script.jsp?a=1&b=2",true);
xmlHttpRequest.send("c=3&d=4");

Leave a comment

Your email address will not be published. Required fields are marked *