为了解决一个PHP AJAX请求转发器的AJAX“同源策略”,code? [英] To get around the ajax 'same origin policy', code for a PHP ajax request forwarder?
问题描述
我想通过让我的网站上的PHP页面,基本上就像一个JSON代理绕过AJAX同源策略。例如我作出这样一个Ajax请求:
I want to bypass the ajax same-origin policy by having a php page on my site that basically acts like a JSON proxy. Eg i make an ajax request like this:
mysite.com/myproxy.php?url=blah.com/api.json&a=1&b=2
然后,它发出请求:
It then makes a request to:
blah.com/api.json?a=1&b=2
和返回JSON(或其他)导致原来的请求。 现在,我想我会是愚蠢重新发明轮子,如果我写的这个PHP code(再加上我不知道PHP的!) - 是有一些pre-现有code做到这一点?我敢肯定,我不是谁的对接我的头反对前同源策略的唯一的一个。
And returns the JSON (or whatever) result to the original requester. Now i assume i'd be stupidly reinventing the wheel if i wrote this php code (plus i don't know php!) - is there some pre-existing code to do this? I'm sure i'm not the only one who's butted my head up against the same-origin policy before.
噢JSONP是不是这个特定API的一个选项。
Oh yeah JSONP isn't an option for this particular api.
感谢所有
推荐答案
好了,这里的东西 - 拍这个成PHP脚本,调用它 script.php的?URL =等等
Okay, here's something - Slap this into a php script, call it like this script.php?url=blah
上传您想发布到服务器中的内容。
post the contents you want posted to the server.
<?php
$curlPost = http_build_query($_POST);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $_GET['url']);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
$data = curl_exec($ch);
curl_close($ch);
echo json_encode($data);
?>
现在这个脚本是有点过于开放我喜欢,所以要提高安全性,我建议你添加域列表到白名单。
Now this script is a bit too open for my liking, so to increase security I would recommend that you add a list of domains to a white list.
所以这添加到顶部:
$whitelist = array('http://www.google.com','http://www.ajax.com');
$list = array();
foreach($whitelist as $w)
$list[] = parse_url($w,PHP_URL_HOST);
$url = $_GET['url'];
$url = pathinfo($url,PHP_URL_HOST);
if(!in_array($url, $list)) die('no access to that domain');
这篇关于为了解决一个PHP AJAX请求转发器的AJAX“同源策略”,code?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!