如何将 cookie 保存到文件中并在其他请求中使用?

How to save cookie into a file and use that in other requests?

我正在通过 Guzzle 登录页面。它正在保存 cookie。当我提出后续请求时,它工作得很好。但是,当我再次 运行 php 时,我不希望 php 执行与登录相同的过程,再次获取 cookie。所以,我想使用现有的 cookie,但我无法做到这一点。我不认为 Guzzle Documentation 对此有很好的解释 基本上,步骤必须是这样的:

  1. php运行第一次登录时,会登录url。 得到饼干。将 cookie 保存到磁盘。用于后续 要求。
  2. 再次php运行时,必须检查cookie是否存在或 不是。如果不去第一步。如果存在,请使用请求的 cookie 文件。

我的class如下。这里的问题是,当 php 运行 第二次时,我需要重新登录。

<?php
namespace OfferBundle\Tools;
use GuzzleHttp\Client;
use GuzzleHttp\Cookie\FileCookieJar;

class Example
{
private $site;
private static $client;
private static $cookieCreated = false;
private static $cookieExists;
private static $loginUrl = "http://website.com/account/login";
private static $header = [
    'Content-Type' => 'application/x-www-form-urlencoded',
    'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; WOW64)'
];
private static $cookieFile = 'cookie.txt';
private static $cookieJar;

private static $credential = array(
    'EmailAddress' => 'username',
    'Password'     => 'password',
    'RememberMe' => true
);

public function __construct($site) {
    self::$cookieExists = file_exists(self::$cookieFile) ? true : false;

    self::$cookieJar = new FileCookieJar(self::$cookieFile, true);
    self::$client = new Client(['cookies' => self::$cookieJar]);

    if(!self::$cookieCreated && !self::$cookieExists) {
        self::createLoginCookie();
    }
    $this->site = $site;
}

public function doSth()
{
   $url = 'http://website.com/'.$this->site;
   $result = (String)self::$client->request('GET',$url, ['headers' => self::$header])->getBody();
    return $result;
}


private static function createLoginCookie()
{
    self::$client->request('POST', self::$loginUrl, [
        'form_params' => self::$credential,
        'connect_timeout' => 20,
        'headers' => self::$header
    ]);
    self::$cookieCreated = true;
}

执行php:

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use OfferBundle\Tools\Example;

class DefaultController extends Controller
{
/**
 * @Route("/")
 */
public function indexAction()
{

    $sm = new Example('anothersite.com');
    $result = $sm->doSth();
    dump($summary);

    die;
}
}

这是我的解决方案:

转到vendor/guzzlehttp/guzzle/src/Cookie/FileCookieJar。php

并注释掉析构函数中的$this->save()部分

public function __destruct()
    {
        //$this->save($this->filename);
    }

使用以下流程登录并将cookie保存到'cookie_path'

 $response = self::$client->request('POST', self::$loginUrl, [
            'form_params' => $formData,
            'connect_timeout' => 20,
            'headers' => self::$header,
            'cookies' => new FileCookieJar('cookie_path')
        ]);

如果您希望默认情况下在所有请求中使用您保存的 cookie,请创建另一个客户端对象并将 cookie 传递给构造函数。

$new_client = new Client(['cookies' => new FileCookieJar('cookie_path')])

现在,您的新客户端已准备好在您的所有请求中使用 cookie。