好的我正在尝试使用PHP代理访问某些JSON,因为我被告知当您不控制站点策略时,这是进行跨域访问的唯一方法。
下面的代码我试图用作由一个stackoverflow用户共享的php代理:
function curl_download($Url){
// is cURL installed yet?
if (!function_exists('curl_init')){
die('Sorry cURL is not installed!');
}
// OK cool - then let's create a new cURL resource handle
$ch = curl_init();
// Now set some options (most are optional)
// Set URL to download
curl_setopt($ch, CURLOPT_URL, $Url);
// Set a referer
curl_setopt($ch, CURLOPT_REFERER, "http://www.example.org/yay.htm");
// User agent
curl_setopt($ch, CURLOPT_USERAGENT, "MozillaXYZ/1.0");
// Include header in result? (0 = yes, 1 = no)
curl_setopt($ch, CURLOPT_HEADER, 0);
// Should cURL return or print out the data? (true = return, false = print)
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Timeout in seconds
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
// Download the given URL, and return output
$output = curl_exec($ch);
// Close the cURL resource, and free system resources
curl_close($ch);
return $output;
}
问题是当我用http://www.nfl.com/liveupdate/scorestrip/ss.json替换$ URL时似乎没有发生任何事情。我不确定如何使用这个PHP代理,因为我从来没有做过这种类型的事情。
我想在一个单独的php文件中创建它,然后向此代码发送请求?我在这方面做了什么准备,以便我可以从上面的网站访问json。
答案 0 :(得分:1)
我想在一个单独的php文件中创建它,然后向此代码发送请求吗?
是。上面的代码应该将您的JS请求重新发送到另一个域上的远程服务。这就是诀窍 - 启用来自JS的跨域POST请求。
<?php
$server_url = "http://example.com/";
$options = array
(
CURLOPT_HEADER => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_TIMEOUT => 60,
CURLOPT_CONNECTTIMEOUT => 0,
CURLOPT_HTTPGET => 1
);
$service = $_GET["service"];
$request_headers = Array();
foreach($_SERVER as $i=>$val) {
if (strpos($i, 'HTTP_') === 0) {
$name = str_replace(array('HTTP_', '_'), array('', '-'), $i);
if ($name != 'HOST')
{
$request_headers[] = "{$name}: {$val}";
}
}
}
$options[CURLOPT_HTTPHEADER] = $request_headers;
switch (strtolower($_SERVER["REQUEST_METHOD"]))
{
case "post":
$options[CURLOPT_POST] = true;
$url = "{$server_url}/services/".$service;
$options[CURLOPT_POSTFIELDS] = file_get_contents("php://input");
break;
case "get":
unset($_GET["service"]);
$querystring = "";
$first = true;
foreach ($_GET as $key => $val)
{
if (!$first) $querystring .= "&";
$querystring .= $key."=".$val;
$first = false;
}
$url = "{$server_url}/services/".$service."?".$querystring;
break;
default:
throw new Exception("Unsupported request method.");
break;
}
$options[CURLOPT_URL] = $url;
$curl_handle = curl_init();
curl_setopt_array($curl_handle,$options);
$server_output = curl_exec($curl_handle);
curl_close($curl_handle);
$response = explode("\r\n\r\n",$server_output);
$headers = explode("\r\n",$response[0]);
foreach ($headers as $header)
{
if ( !preg_match(';^transfer-encoding:;ui', Trim($header)) )
{
header($header);
}
}
echo $response[1];
这是我使用的脚本的略微修改版本,遗憾的是没有详细记录。
希望它有所帮助。
答案 1 :(得分:0)
我建议使用Ben Almans Simple PHP Proxy