2012-11-09 78 views
0

我正在一个项目中,我正在使用api与一个单独的网站上的电子商务商店接口。我可以通过API将项目添加到篮子,并使用cURLS CookieJar保存状态。结帐时,我只想链接到主电子商务网站上的实际结帐流程。我需要能够将存储在CookieJar中的Cookie与重定向请求一起发送。设置请求Cookies保存在cURL Cookie重定向CookieJar文件

我试图用cURL来抓取cookie,然后按照重定向,但我误解了它是如何工作的。它不是重定向浏览器,而是基于302重定向发出新的cURL请求。

$curlopt = array(
    CURLOPT_COOKIEJAR => xxx, // this is the path to the cookie file 
    CURLOPT_COOKIEFILE => xxx, // this is the path to the cookie file 
    CURLOPT_FOLLOWLOCATION => true, 
    CURLOPT_AUTOREFERER => true, 
    CURLOPT_URL => 'http://mydomain.com/redirect_to_ecommerce_checkout.php' 
); 

$ch = curl_init(); // run curl 
curl_setopt_array($ch, $curlopt); 
curl_exec($ch); 
curl_close($ch); 

这似乎给正确的Cookie发送到电子商务页面,问题是浏览器不重定向,而是呈现出从我的域名的主要电子商务网站的HTML。

如何设置请求cookie并实际执行重定向?

在此先感谢。

回答

0

我想你只需要告诉CURL给你的标题,而不是遵循重定向。然后,您可以解析“位置:”标题。事情是这样的:

$curlopt = array(
    CURLOPT_COOKIEJAR => xxx, // this is the path to the cookie file 
    CURLOPT_COOKIEFILE => xxx, // this is the path to the cookie file 
    CURLOPT_FOLLOWLOCATION => false, // <--- change to false so curl does not follow redirect 
    CURLOPT_AUTOREFERER => true, 
    CURLOPT_URL => 'http://mydomain.com/redirect_to_ecommerce_checkout.php', 
    CURLOPT_HEADER => true, 
    CURLOPT_RETURNTRANSFER => true // Return transfer string instead of outputting directly 
); 

$ch = curl_init($url); 
curl_setopt_array($ch, $curlopt); 
$response = curl_exec($ch); // save response to a variable 
curl_close($ch); 

// try to find Location header in $response 
preg_match_all('/^Location:(.*)$/mi', $response, $matches); 

if (!empty($matches[1])) { 
    header("Location: " . trim($matches[1][0])); 
    exit; 
} 
else { 
    echo 'No redirect found'; 
} 

注意我设置CURLOPT_FOLLOWLOCATION =>假,CURLOPT_HEADER => true,并且CURLOPT_RETURNTRANSFER => true,然后视察了curl_exec()的响应,我保存在$响应。

您也可以尝试:

header("Location: " . curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);