我正通过Guzzle登录页面。它正在保存cookie。当我做出后续请求时,它完全正常。但是,当我再次运行php时,我不希望php执行相同的登录过程,再次获取cookie。所以,我想使用现有的cookie,但我无法做到这一点。我不认为在Guzzle Documentation得到了很好的解释 基本上,步骤必须是这样的:
我的课程如下。这里的问题是,当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;
}
}
答案 0 :(得分:1)
这是我的解决方案:
转到vendor / guzzlehttp / guzzle / src / Cookie / FileCookieJar.php
并在析构函数中注释掉$ this-&gt; save()部分。
public function __destruct()
{
//$this->save($this->filename);
}
使用以下过程登录并将Cookie保存到&#39; cookie_path&#39;
$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。