php服务器代理解决浏览器跨越问题

详见代码

<?php

$url = $_SERVER["QUERY_STRING"];

switch ($_SERVER['REQUEST_METHOD']) {
case "GET":
curlget($url);
break;
case "POST":
$CONTENT_TYPE = explode(';',$_SERVER['CONTENT_TYPE']);
switch($CONTENT_TYPE[0]) {
case 'application/x-www-form-urlencoded':
$data = http_build_query($_POST);
break;
case 'multipart/form-data':
$tempname = $_FILES['file']['tmp_name'];
$basename = basename($_FILES['file']['name']);
$origname = sys_get_temp_dir() . '/' . $basename;
move_uploaded_file($tempname, $origname);
chdir(sys_get_temp_dir());
$data = array('name' => 'file', 'filename' => '@' . $basename);
break;
default:
exit;
}
curlpost($url, $data);
break;
default:
exit;
} function curlget($url) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if (strpos($url,"https") >= 0) {
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
}
$data = curl_exec($ch);
if ($data === false) {
header('HTTP/1.1 400 Bad Request');
exit;
} else {
echo $data;
}
} function curlpost($url, $data) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
if (strpos($url,"https") >= 0) {
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
}
$data = curl_exec($ch);
if ($data === false) {
header('HTTP/1.1 400 Bad Request');
exit;
} else {
echo $data;
}
}
?>

如何使用:

1.把上面代码建立一个proxy.php的文件,放到PHP的后台服务器

2.在浏览器端用js访问,以jquery代码为例

$.ajax({
url: "http://www.phphost.com/proxy.php?https://www.example.com/someApi",
type: 'post',
data: {
a: "123",
b: "456"
},
dataType: 'json',
success: function(result){
// do some things
}
});

其中访问地址的格式是 PHP服务器地址+/proxy.php? + 需要跨域访问的接口;get、post 请求均可;

借鉴了https://www.cnblogs.com/zoho/archive/2012/07/03/2575380.html这里的代码,

增加了对https协议的支持。

由于本人PHP代码不精通,未做安全检测,自己测试够用。

上一篇:APP端测试与web端测试的区别


下一篇:How to set up a basic working Appium test environment