php 是否可以使用 CURL 设置 cookie 内容?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10570341/
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
Is it possible to set the cookie content with CURL?
提问by Ahatius
I have been searching for a way, to specify the cookie data for CURL. I have found some solutions on how to save the cookies from a visited page, but that's not what I need. What I want is, to write the data for the cookie myself, so CURL uses it.
我一直在寻找一种方法,为 CURL 指定 cookie 数据。我找到了一些关于如何从访问过的页面保存 cookie 的解决方案,但这不是我需要的。我想要的是,自己为cookie写数据,所以CURL使用它。
回答by vvondra
You can use curl_setoptwith the CURLOPT_COOKIE constant:
您可以使用curl_setoptCURLOPT_COOKIE 常量:
<?php
// create a new cURL resource
$ch = curl_init();
// cookies to be sent
curl_setopt($ch, CURLOPT_COOKIE, "fruit=apple; colour=red");
回答by Mahmoud Al-Qudsi
You really should read the documentation- it's listed with exactly the keywords you'd expect and contains a lot of helpful info:
您真的应该阅读文档- 它列出了您期望的关键字,并包含许多有用的信息:
-b, --cookie
(HTTP) Pass the data to the HTTP server as a cookie. It is supposedly the data previously received from the server in a "Set-Cookie:" line. The data should be in the format "NAME1=VALUE1; NAME2=VALUE2".
If no '=' symbol is used in the line, it is treated as a filename to use to read previously stored cookie lines from, which should be used in this session if they match. Using this method also activates the "cookie parser" which will make curl record incoming cookies too, which may be handy if you're using this in combination with the -L, --location option. The file format of the file to read cookies from should be plain HTTP headers or the Netscape/Mozilla cookie file format.
NOTE that the file specified with -b, --cookie is only used as input. No cookies will be stored in the file. To store cookies, use the -c, --cookie-jar option or you could even save the HTTP headers to a file using -D, --dump-header!
If this option is set more than once, the last one will be the one that's used.
-b, --cookie
(HTTP) 将数据作为 cookie 传递到 HTTP 服务器。它应该是先前在“Set-Cookie:”行中从服务器接收到的数据。数据的格式应为“NAME1=VALUE1;NAME2=VALUE2”。
如果行中未使用“=”符号,则将其视为文件名,用于从中读取先前存储的 cookie 行,如果匹配,则应在此会话中使用。使用此方法还会激活“cookie 解析器”,它也会使 curl 记录传入的 cookie,如果您将它与 -L、--location 选项结合使用,这可能会很方便。要从中读取 cookie 的文件的文件格式应该是纯 HTTP 标头或 Netscape/Mozilla cookie 文件格式。
请注意,使用 -b, --cookie 指定的文件仅用作输入。文件中不会存储任何 cookie。要存储 cookie,请使用 -c, --cookie-jar 选项,或者您甚至可以使用 -D, --dump-header 将 HTTP 标头保存到文件中!
如果此选项设置多次,最后一个将是使用的那个。
回答by Emil Vikstr?m
cURL can use a cookie file in Netscape format. Just create such a file yourself and use as the CURLOPT_COOKIEFILEoption.
cURL 可以使用Netscape 格式的 cookie 文件。只需自己创建一个这样的文件并用作CURLOPT_COOKIEFILE选项。

