【问题标题】:Setting Request Cookies in Redirect saved in cURL CookieJar File在保存在 cURL CookieJar 文件中的重定向中设置请求 Cookie
【发布时间】:2023-03-13 12:35:02
【问题描述】:

我正在开展一个项目,我正在使用 api 与单独网站上的电子商务商店进行交互。我可以通过 api 将项目添加到购物篮,并使用 cURLS CookieJar 来保存状态。要结帐,我只想链接到主要电子商务网站上的实际结帐流程。但是,我需要能够将存储在 CookieJar 中的 cookie 与重定向请求一起发送。

我尝试使用 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 并实际执行重定向?

提前致谢。

【问题讨论】:

    标签: php redirect cookies curl redirectwithcookies


    【解决方案1】:

    我认为你只需要告诉 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 => false、CURLOPT_HEADER => true 和 CURLOPT_RETURNTRANSFER => true,然后检查了我保存在 $response 中的 curl_exec() 响应。

    你也可以试试:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-06-13
      • 2014-10-27
      • 2015-04-18
      • 1970-01-01
      • 2020-06-27
      • 2015-03-22
      • 2015-08-25
      相关资源
      最近更新 更多