【发布时间】:2017-04-03 07:24:47
【问题描述】:
我正在通过 Guzzle 登录一个页面。它正在保存cookie。当我提出后续请求时,它工作得非常好。但是,当我再次运行 php 时,我不希望 php 执行相同的登录过程,再次获取 cookie。所以,我想使用现有的 cookie,但我无法做到。我认为Guzzle Documentation 没有很好地解释它 基本上,步骤必须是这样的:
- php第一次运行时,会登录到url。 得到饼干。将 cookie 保存到磁盘。后续使用 要求。
- 当php再次运行时,它必须检查cookie是否存在或 不是。如果不去第一步。如果存在,请为请求使用 cookie 文件。
我的课如下。这里的问题是,当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;
}
}
【问题讨论】:
标签: php symfony curl guzzle guzzle6