Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting up cookies for Guzzle CookieJar

I am doing unit testing in PHP for a site that requires authentication. Authentication is cookie based, so I need to be able to put a cookie like this in the cookie jar:

[ 'user_token' => '2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae' ] 

The web application can then use this known good token for the testing data, and will be able to authenticate under testing conditions to interact with the data fixtures.

Also, it must be a secure cookie, and I (obviously) need to set the domain.

Problem is: I don't know how to make and set this cookie and stick it in the jar. How do you do that?

like image 494
DrDamnit Avatar asked Feb 05 '17 21:02

DrDamnit


Video Answer


2 Answers

Simple example. this code is saving cookie in a file and loading it back next time you execute the script

use GuzzleHttp\Client;
use GuzzleHttp\Cookie\FileCookieJar;

// file to store cookie data
$cookieFile = 'cookie_jar.txt';

$cookieJar = new FileCookieJar($cookieFile, TRUE);

$client = new Client([ 
  'base_uri' => 'http://example.com',
  // specify the cookie jar
  'cookies' => $cookieJar
]);

// guzzle/cookie.php, a page that returns cookies.
$response = $client->request('GET', 'simple-page.php');

session cookies are not stored automatically. To store the php session cookie we must set the second parameter to TRUE.

$cookieJar = new FileCookieJar($cookieFile, TRUE);

Reference

http://www.ryanwright.me/cookbook/guzzle/cookie

like image 85
Abdullah Mallik Avatar answered Oct 16 '22 13:10

Abdullah Mallik


The source code provided the answer I needed.

The CookieJar class provides a method for building cookies from an associative array. Example:

$domain = 'example.org';
$values = ['users_token' => '2c26b46b68ffc68ff99b453c1d30113413422d706483bfa0f98a5e886266e7ae'];

$cookieJar = \GuzzleHttp\Cookie\CookieJar::fromArray($values, $domain);

$client = new \GuzzleHttp\Client([
    'base_uri' => 'https://example.org',
    'cookies'  => $cookieJar 
]);
like image 43
DrDamnit Avatar answered Oct 16 '22 15:10

DrDamnit