php - Goutte 客户端将 cookie 保存到文件

如何配置 Goutte Client 使用文件将 cookie 存储在文件中?我知道它是一种围绕 GuzzleHttp 客户端的包装器。但我无法将其配置为将 cookie 保存到文件中以在请求之间重用它们。

尝试扩展 Goutte 客户端,doRequest 方法,但我不明白如何正确执行此操作。

有没有人用过 Goutte Client 把 cookie 保存到文件?

最佳答案

我认为没有一种简单的方法可以实现这一点,因为 Goutte 强制使用 guzzle 的 CookieJar 类,该类在脚本执行后不会持续存在。通过你自己的类(class)来使用像 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));
    }
}

https://stackoverflow.com/questions/32936480/

相关文章:

drupal - 如何在更新模块之前检查是否需要更新数据库

layout - matplotlib:获取子图布局?

php - 如何使用 FDI/FPDF 从 PDF 中删除文本

Emacs - 多行搜索

arrays - 如何证明从完全二叉树到数组的转换?

codeigniter - 如何从 codeigniter 中的另一个 Controller 调用

javascript - 纯函数是幂等的吗?

math - XOR 在数学上有什么作用?

google-sheets - 将字符串转换为可以传递给函数的单元格引用

cross-compiling - Clang++ 无法找到任何 stdlib header