Reputation: 146
The Guzzle site is very weak documentation. I realized that I needed to look at the source code to use all the features of the library, but I still can not fully understand the source code.
How to get cookies with Guzzle from any website? What class to look at?
Upvotes: 1
Views: 3058
Reputation:
The cookies representation in guzzle is part of the PSR-7's ServerRequestInterface
implementation, e.g of the ServerRequest
class. In the class is defined an array property $cookieParams
. To this variable you can either assign the $_COOKIE
variable (through the call to the static method fromGlobals()
) or an array of your choice (inclusive $_COOKIE
) by calling withCookieParams()
. To read the content of the $cookieParams
array you just need to call getCookieParams()
.
Example using fromGlobals()
- having the role of a ServerRequest
factory:
<?php
use GuzzleHttp\Psr7\ServerRequest;
/**
* Create a ServerRequest instance, populated with superglobals:
* $_GET
* $_POST
* $_COOKIE
* $_FILES
* $_SERVER
*/
$serverRequest = ServerRequest::fromGlobals();
// Display the content of $_COOKIE.
var_dump($serverRequest->getCookieParams());
Example of directly creating a ServerRequest
instance and assigning a cookies array to a copy of it - in order to maintain the immutability of the request object:
<?php
use GuzzleHttp\Psr7\ServerRequest;
// Directly create a ServerRequest instance.
$serverRequest = new ServerRequest('GET', 'http://localhost/mypath?var=somevar#myfragment', [], NULL, '1.1', $_SERVER);
// Create a clone instance with the specified cookies array.
$serverRequest = $serverRequest->withCookieParams($_COOKIE);
// Display the content of the cookies list.
var_dump($serverRequest->getCookieParams());
There is also another implementation, the one of GuzzleHttp\Cookie\CookieJarInterface
, e.g the class GuzzleHttp\Cookie\CookieJar
(see here) This is documented on http://docs.guzzlephp.org, at:
In CookieJar
class you can assign a $cookieArray
in constructor and have some methods to handle its values (getCookieValue()
, getCookieByName()
, setCookie()
etc).
Upvotes: 1