【问题标题】:How to connecting to the remote site with CURL and header location如何使用 CURL 和标头位置连接到远程站点
【发布时间】:2018-06-22 19:19:56
【问题描述】:

我通过站点 B 上的 CURL 从站点 A 登录,我从连接中获取 cookie 并写入名为 cookie.txt 的文件。

但是当我传递 cookie 数据进行最终的标头重定向时('Location: http://examplesiteb.com'),它返回断开连接。

我用于连接的代码与其他帖子中的代码相同,但我根据@ramrider 用户的建议进行了修改,我建议在标题中传递 cookie,但我不确定应该如何完成.

Transfer cookies & session from CURL to header location

  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_POST, true);
  curl_setopt($ch, CURLOPT_COOKIESESSION, true);
  curl_setopt($ch, CURLOPT_HEADER, true);
  curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
  curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
  curl_setopt($ch, CURLOPT_FRESH_CONNECT, 10);
  curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt');
  curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookie.txt');

  // Download the given URL, and return output
  $output = curl_exec($ch);

  // Cookie Match
  preg_match_all('/^Set-Cookie:\s*([^\r\n]*)/mi', $output, $ms);

  $cookies = array();
  foreach ($ms[1] as $m) {
    list($name, $value) = explode('=', $m, 2);
    $cookies[$name] = $value;

    header('Set-Cookie: '.rawurlencode($name).'='.rawurlencode($value));
  }

  //print_r($cookies);

  $redirect = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);

  header("Location: $redirect");

  //Close Match
  curl_close($ch);

重定向发生但不保持登录状态。

在示例 cookie 文件下方

# Netscape HTTP Cookie File
# http://curl.haxx.se/docs/http-cookies.html
# This file was generated by libcurl! Edit at your own risk.

#HttpOnly_example.com   FALSE   /   FALSE   0   ASP.NET_SessionId   10gtonkebkteuazx24sajlh2
#HttpOnly_example.com   FALSE   /   TRUE    1515800212  DTE 898EC9C0EF0BA3985E402046547931EAA55808E14A2DE469F11F6F6C0CF9A28871C8704BE794885CDF7D3EE1E8B06698166F86C184C5B53FE61FA53CA13682C562E17BCB7B2FA16D7A7180E6EA973735

如果用户 @martijn-pieters 和 @waqas-bukhary 可以提供帮助,我将感谢您,因为您删除了我在另一篇帖子中的答案,并且我正在为其他人完成我无法找到解决方案的其他信息。

谢谢

【问题讨论】:

    标签: php curl cookies session-cookies


    【解决方案1】:

    Cookie 与发送它们的域相关联。您不能为其他域设置 cookie。

    如果“站点 B”(您使用 cURL 登录“站点 A”)是 example.com,而“站点 A”是 not-example.com,则由 Set-Cookie 设置的 cookie 是针对 example.com并且不适用于not-example.com

    没有任何机制可以为您自己的域以外的域设置 cookie。

    参见RFC 6265 第 5.3 节(存储模型)第 6 部分:

    如果域属性不为空:

    • 如果规范化的请求主机与域属性不匹配:

      • 完全忽略 cookie 并中止这些步骤。

    这实际上表明如果站点 A 尝试为站点 B 设置 cookie,浏览器必须忽略 cookie。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-26
      • 1970-01-01
      • 2021-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-09
      相关资源
      最近更新 更多