Fatih Yavuz Fatih Yavuz -4 years ago 123
PHP Question

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

I'm logging in to a page through Guzzle. It's saving the cookie. When I make subsequent requests it works perfectly fine. But, when I run the php again, I don't want php to do the same process which is logging in, getting the cookie again. So, I want to use existing cookie but I could not manage to do that. I don't think that it is well explained at Guzzle Documentation
Basically, steps must be like this:


  1. When the php runs for the first time, it will login to the url.
    get the cookies. Save the cookies to the disk. Use it for subsequent
    requests.

  2. When php runs again, it must check if cookie exists or
    not. if not go to first step. If exists, use the cookie file for the requests.



My class is as following. The problem here is, when php runs 2nd time, I need to log in again.

<?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;
}


Executed 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;
}
}

Answer Source

Here is my soluion:

Go to vendor/guzzlehttp/guzzle/src/Cookie/FileCookieJar.php

And comment out $this->save() part in the destructor.

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

Use the following process to login and save the cookie to 'cookie_path'

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

If you want your saved cookie to be used in all your requests by default, create another client object and pass the cookie to the constructor.

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

Now, your new client is ready to use the cookie in all of your requests.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download