Goutte客户端将Cookie保存到文件
问题描述:
如何配置Goutte客户端以使用文件将Cookie存储在文件中?我知道它是GuzzleHttp客户端的一种包装。但我无法将其配置为将Cookie保存到文件以在请求之间重复使用它们。Goutte客户端将Cookie保存到文件
试图扩展Goutte客户端,方法doRequest
,但我不明白如何正确执行此操作。
有没有人使用Goutte客户端cookie保存到文件?
答
我不认为有一种简单的方法可以实现这一点,因为Goutte强制使用guzzle的CookieJar类,该类在脚本执行后不会保留。将自己的类传递给像FileCookieJar这样的东西会非常棒,但是由于CookieJar的硬编码调用,这是不可能的(有人为它创建了一个PR,但是现在已经有几个月了,里面没有任何最近的活动Goutte项目)。
可以做的是创建访问BrowserKit CookieJar并存储其内容的方法。一些示例代码如下:
// Will hold path to a writable location/file
protected $cookieFilePath;
public function setCookieFilePath($cookieFilePath)
{
$this->cookieFilePath = $cookieFilePath;
if (is_file($cookieFilePath)) {
// Load cookies and populate browserkit's cookie jar
$cookieJar = $this->client->getCookieJar();
$cookies = unserialize(file_get_contents($cookie));
foreach ($cookies as $cookie) {
$cookieJar->set($cookie);
}
}
}
// Call this whenever you need to save cookies. Maybe after a request has been made since BrowserKit repopulates it's CookieJar from the Response returned.
protected function saveCookies()
{
$cookieFilePath = $this->getCookieFilePath();
$goutteClient = $this->getGoutteClient();
$cookieJar = $goutteClient->getCookieJar();
$cookies = $cookieJar->all();
if ($cookies) {
file_put_contents($cookieFilePath, serialize($cookies));
}
}
是的。这个想法很好。很难过,8个月没有更新:( – SpartakusMd