PHP代理服务器和调用JSON? [英] PHP Proxy Server and Calling JSON?

查看:324
本文介绍了PHP代理服务器和调用JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我试图使用PHP代理访问一些JSON,因为我被告知是当你不控制网站的政策,做一个跨域访问的唯一方法。



这里是我试图使用php代理作为一个同事stackoverflow用户共享:

  function curl_download($ Url){

//是cURL安装了吗?
if(!function_exists('curl_init')){
die('Sorry cURL is not installed!');
}

// OK cool - 然后让我们创建一个新的cURL资源句柄
$ ch = curl_init();

//现在设置一些选项(大多数是可选的)

//设置要下载的URL
curl_setopt($ ch,CURLOPT_URL,$ Url);

//设置引用
curl_setopt($ ch,CURLOPT_REFERER,http://www.example.org/yay.htm);

//用户代理
curl_setopt($ ch,CURLOPT_USERAGENT,MozillaXYZ / 1.0);

//在result中包含标题? (0 = yes,1 = no)
curl_setopt($ ch,CURLOPT_HEADER,0);

//应该cURL返回或打印出数据吗? (true = return,false = print)
curl_setopt($ ch,CURLOPT_RETURNTRANSFER,true);

//超时(以秒为单位)
curl_setopt($ ch,CURLOPT_TIMEOUT,10);

//下载给定的URL,并返回输出
$ output = curl_exec($ ch);

//关闭cURL资源,释放系统资源
curl_close($ ch);

return $ output;问题是当我用替换$ URL时,会出现


$ b < /www.nfl.com/liveupdate/scorestrip/ss.jsonrel =nofollow> http://www.nfl.com/liveupdate/scorestrip/ss.json
似乎没有发生。我不是真的确定如何使用这个PHP代理,虽然或者,因为我从来没有做这种类型的事情。



我想在一个单独的php文件中创建这个,然后发送一个请求到这个代码?

解决方案

blockquote>

我假设要在一个单独的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 'HTTP_','_'),array('',' - '),$ i);
if($ name!='HOST')
{
$ request_headers [] ={$ name}:{$ val};
}
}
}

$ options [CURLOPT_HTTPHEADER] = $ request_headers;

switch(strtolower($ _ SERVER [REQUEST_METHOD]))
{

casepost:
$ options [CURLOPT_POST] = true ;
$ url ={$ server_url} / services /。

$ options [CURLOPT_POSTFIELDS] = file_get_contents(php:// input);

break;
caseget:

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;
默认值:
throw new Exception(不支持的请求方法。
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\\\
\r\\\
,$ server_output);
$ headers = explode(\r\\\
,$ response [0]);

foreach($ headers as $ header)
{
if(!preg_match('; ^ transfer-encoding:; ui',Trim($ header)))
{
header($ header);
}
}

echo $ response [1];

这是我使用的脚本略有修改的版本,

希望它有帮助。


Ok I am trying to access some JSON using a PHP proxy as I have been told is the only way to do a cross domain access when you don't control the sites policies.

Here is the code below I am trying to use as a php proxy as shared by a fellow stackoverflow user:

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;
}

problem is when I replace $URL with http://www.nfl.com/liveupdate/scorestrip/ss.json nothing seems to happen. I am not really sure how to use this PHP proxy though either as I don't ever do this type of thing.

Am I suppose to create this in a seperate php file and then send a request to this code? I am kind of against the wall on what exactly to do here to make it so I can access the json from the site above.

解决方案

Am I suppose to create this in a seperate php file and then send a request to this code?

Yes. The code above should resend your request made from JS to a remote service on another domain. Which is what does the trick - enables crossdomain POST requests from JS.

<?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]; 

This is a slightly modified version of the script I use, unfortunately not well documented.

Hope it helps.

这篇关于PHP代理服务器和调用JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆