2012-11-09 77 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);