PHP 和 cURL 使用现有的 COOKIEFILE + 添加我自己的值来保存


PHP & cURL to use existing COOKIEFILE + Adding my own value to save

我已经保存了一个想要引用和更新的cookie文件。 我还想通过CURLOPT_COOKIE指定我自己的其他 cookie 值,并将其保存到我现有的 cookie 文件中。

但是,我无法让它工作。

我的代码是:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $website); // Define target site
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); // Return page in string
curl_setopt($ch, CURLOPT_ENCODING , "gzip");
curl_setopt($ch, CURLOPT_COOKIE, "fruit=apple;");          
curl_setopt($ch, CURLOPT_COOKIEJAR, "usercookies/cookie_$user.txt"); // Tell cURL where to write cookies
curl_setopt($ch, CURLOPT_COOKIEFILE, "usercookies/cookie_$user.txt"); // Tell cURL which cookies to send
curl_setopt($ch, CURLOPT_TIMEOUT,15); 
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE); // Follow redirects
$returnx = curl_exec($ch); 
$info = curl_getinfo($ch); 
curl_close($ch); 

保存的 cookie 文件没有反映我通过 curl_setopt($ch, CURLOPT_COOKIE, "fruit=apple;"); 所做的更改。 保存的 cookie 文件应显示"fruit=apple",但它仍显示旧值或 cURL 请求返回的值。

我是否需要引用整个域名才能保存?

cookie 文件如下所示:

# Netscape HTTP Cookie File
# http://curl.haxx.se/docs/http-cookies.html
# This file was generated by libcurl! Edit at your own risk.
.go.com TRUE    /   FALSE   1754020486  one AE4F4981
.go.com TRUE    /   FALSE   1468965260  two B9A1
您使用

CURLOPT_COOKIE手动添加的 Cookie 不会在请求结束时保存到 cookie jar 中。

唯一的情况是服务器为您发送的cookie发回Set-Cookie标头以进行更新。

原因是因为 cURL 请求有一个 cookie 结构,其中包含在请求末尾写入的 cookie。 数据只能通过 a) 首先从 cookie 文件中读取或 b) 在响应标头中Set-Cookie标头来进入此结构。

稍微小心一点,您可以使用如下所示的内容将自己的cookie附加到该文件中:

$domain = '.go.com';
$expire = time() + 3600;
$name   = 'fruit';
$value  = 'apple';
file_put_contents($cookieJar, "'n$domain'tTRUE't/'tFALSE't$expire't$name't$value", FILE_APPEND);