bash 使用 cURL 获取当前会话的 cookie

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28070500/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 12:13:08  来源:igfitidea点击:

Grab current session's cookie with cURL

bashcurlcookies

提问by Nhoya

I'm working on a script that send a POST request to an URL, actually I'm sending the cookies manually in the header.. but how to take it from the current browser session?

我正在编写一个向 URL 发送 POST 请求的脚本,实际上我在标题中手动发送 cookie ..但是如何从当前浏览器会话中获取它?

I used tcpdump and grep but it's really the wrong choice :,D Some suggestions?

我使用了 tcpdump 和 grep 但它确实是错误的选择 :,D 一些建议?

I wont take them from a file but from the browser session and without enter in the cookie path of the browser

我不会从文件中获取它们,而是从浏览器会话中获取它们,而无需输入浏览器的 cookie 路径

回答by nlu

Curl can handle that for you; there is an option to store the cookies in a cookiejar and use those in subsequent requests.

Curl 可以为您处理;可以选择将 cookie 存储在 cookiejar 中并在后续请求中使用它们。

Here is an example from the main curl site, which uses cookies from a file cookies.txt to set some and at the same time stores new cookies in newcookies.txt.

下面是来自主要 curl 站点的示例,它使用文件 cookies.txt 中的 cookie 来设置一些,同时在 newcookies.txt 中存储新的 cookie。

http://curl.haxx.se/docs/httpscripting.html#Cookie_Basics

http://curl.haxx.se/docs/httpscripting.html#Cookie_Basics

curl --cookie cookies.txt --cookie-jar newcookies.txt  http://www.example.com

When going through a login process, for example, one would reuse the cookies from cookie jar.

例如,在进行登录过程时,人们会重用 cookie jar 中的 cookie。

回答by Alwin Kesler

I had found a link now broken with an example from snipplr.com. I'll post it here for future references (credits to the owner):

我找到了一个链接,现在有一个来自 snipplr.com 的例子。我会把它贴在这里以供将来参考(感谢所有者):

$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

if (isset($_COOKIE[session_name()])) {
  curl_setopt($ch, CURLOPT_COOKIE, session_name().'='.$_COOKIE[session_name()].'; path=/');
}

session_write_close();
$result = curl_exec($ch);

if (curl_errno($ch)) {
  echo 'curl error: '.curl_error($ch);   
}

curl_close($ch);
session_start();