您可以将curl_setopt 函数与CURLOPT_HTTPHEADER 选项一起使用。
curl_setopt($ch, CURLOPT_HTTPHEADER, ["Cookie: mycookie=value;mycookie2=value2"]);
[编辑]
来自本指南The Unofficial Cookie FAQ。
Netscape 的 cookies.txt 文件的布局使得每一行都包含一个名称-值对。示例 cookies.txt 文件可能包含如下所示的条目:
.netscape.com TRUE / FALSE 946684799 NETSCAPE_ID 100103
每一行代表一条存储的信息。在每个字段之间插入一个选项卡。
从左到右,每个字段代表的内容如下:
域 - 创建并可以读取变量的域。
flag - 一个 TRUE/FALSE 值,指示给定域内的所有机器是否都可以访问该变量。此值由浏览器自动设置,具体取决于您为域设置的值。
path - 变量有效的域中的路径。
secure - 一个 TRUE/FALSE 值,指示是否需要与域的安全连接才能访问变量。
到期 - 变量到期的 UNIX 时间。 UNIX 时间定义为自 1970 年 1 月 1 日 00:00:00 GMT 以来的秒数。
name - 变量的名称。
值 - 变量的值。
回答你的问题
1) 要在发送前稍作修改:
$file = file('cookie.txt');
$cookies = [];
/*
* From the guidelines that I linked and posted above each line must contain 7 "fields" separated by tab only (The text you posted in the question is not well formatted but with some tricks we can do this)
*/
foreach ($file as $fileLine) {
$fileLine = preg_replace("/\s+/", "\t", trim($fileLine));
$fields = explode("\t", $fileLine);
if (count($fields) === 7) {
$cookies[] = [
'domain' => $fields[0],
'flag' => $fields[1],
'path' => $fields[2],
'secure' => $fields[3],
'expiration' => $fields[4],
'name' => $fields[5],
'value' => $fields[6],
];
}
}
var_dump($cookies); // Here you have all lines from your cookie file and can modify the fields such name, value or something
2) 要使用您的修改 cookie 数组覆盖 cookie.txt,请执行以下操作:
// Preserve Netscape format
$cookies = implode(PHP_EOL, array_map(function($data){
return implode("\t", $data);
}, $cookies));
file_put_contents('cookie.txt', $cookies);
3) 要从文件中发送新的 cookie,请执行以下操作(必须为 Netscape 格式):
curl_setopt ($ch, CURLOPT_COOKIEFILE, 'cookie.txt');