cURL和Paypal无法正常工作

时间:2011-07-26 09:49:56

标签: php curl

1 个答案:

答案 0 :(得分:0)

我不确定您是否仍然遇到此问题,我们发现在某些情况下,CURLOPT_FOLLOWLOCATION无法按预期执行。这通常是服务器配置问题,有时候您无法轻易更改。

为了解决这个问题,我们编写了函数(如下),结合CURL调用为我们提供了所需的解决方案:

function curl_redir_exec($ch,$test = false)
    {
    static $curl_loops = 0;
    static $curl_max_loops = 20;
    if ($curl_loops++>= $curl_max_loops)
    {
    $curl_loops = 0;
    return FALSE;
    }
    curl_setopt($ch, CURLOPT_HEADER, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $data = curl_exec($ch);
    list($header, $data) = explode("\n\n", $data, 2);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    if ($http_code == 301 || $http_code == 302)
    {
    $matches = array();
    preg_match('/Location:(.*?)\n/', $header, $matches);
    $url = @parse_url(trim(array_pop($matches)));
    if (!$url){
        //couldn't process the url to redirect to
        $curl_loops = 0;
        return $data;
    }
    $last_url = parse_url(curl_getinfo($ch, CURLINFO_EFFECTIVE_URL));
    if (!$url['scheme'])
    $url['scheme'] = $last_url['scheme'];
    if (!$url['host'])
    $url['host'] = $last_url['host'];
    if (!$url['path'])
        $url['path'] = $last_url['path'];
        $new_url = $url['scheme'] . '://' . $url['host'] . $url['path'] . ($url['query']?'?'.$url['query']:'');
        curl_setopt($ch, CURLOPT_URL, $new_url);
        return $this->curl_redir_exec($ch);
    } else {
        $curl_loops=0;
        if($test){
            return curl_getinfo($ch, CURLINFO_EFFECTIVE_URL).'<br />'.$http_code.'<br />'.$data;
        }else{
            return curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
        }
    }
}

function curl_post_fields($array){
    foreach ($array as $key=>$value){
        $arr_output[] = trim($key).'='.trim($value);
    }
    return preg_replace('#(\r\n|\r|\n)+#m',"",trim(implode('&', $arr_output)));
}

完整的CURL调用如下所示:

$data2 = $fn->curl_post_fields($data1);
$curl_session = curl_init($url);
curl_setopt($curl_session, CURLOPT_URL, $url);
curl_setopt($curl_session, CURLOPT_COOKIESESSION, 1);
curl_setopt($curl_session, CURLOPT_FRESH_CONNECT, 1);
curl_setopt($curl_session, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB;) Firefox/3.6.13");
curl_setopt($curl_session, CURLOPT_HTTPHEADER, array('X-Forwarded-For: '.$_SERVER['REMOTE_ADDR']));
curl_setopt($curl_session, CURLOPT_VERBOSE, 1);
curl_setopt($curl_session, CURLOPT_POST, 1);
curl_setopt($curl_session, CURLOPT_POSTFIELDS, $data2);
curl_setopt($curl_session, CURLOPT_TIMEOUT, 30);
curl_setopt($curl_session, CURLOPT_SSL_VERIFYPEER, FALSE);
$redirect_url = $shop->curl_redir_exec($curl_session);
if(curl_errno($curl_session))
{
    echo '<p>An error has occurred, please take note of the information below and contact support.</p>';
    echo "<br>Errno : ".curl_errno($curl_session) ."<br>";
    echo "<br>Error : ".curl_error($curl_session) ."<br>";
    die();
}
curl_close($curl_session);
header("location:$redirect_url");

我希望这对你有用。