February 23, 2022 . 1 MIN READ
$client->setServerParameter(‘HTTP_USER_AGENT’, ‘Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:73.0) Gecko/20100101 Firefox/73.0’);
use Symfony\Component\BrowserKit\Cookie;
$client->getCookieJar()->set( new Cookie(‘store’, ‘english’) );
$client->getCookieJar()->set( new Cookie(‘currency’, ‘EUR’) );
$client->getCookieJar()->set( new Cookie(‘vat_store_selected’, ‘english’) );
$client->getCookieJar()->set( new Cookie(‘spLang’, ‘en_US’) );
public function testFileCookieJar($testSaveSessionCookie = false)
{
$guzzle = $this->getGuzzle();
$client = new Client();
$client->setClient($guzzle);
$filename = tempnam(‘/tmp’, ‘file-cookies’);
$jar = new FileCookieJar($filename, $testSaveSessionCookie);
$client->setGuzzleCookieJar($jar);
$client->getCookieJar()->set(new Cookie(‘test’, ‘123’));
$client->getCookieJar()->set(new Cookie(‘foo’, ‘bar’, time() + 1000));
$client->request(‘GET’, ‘http://www.example.com/’);
// Call to destruct method manually to test saving cookies
$jar->__destruct();
// Make sure it wrote to the file
$contents = file_get_contents($filename);
$this->assertNotEmpty($contents);
// Load the cookieJar from the file
$cookieJarReloaded = new FileCookieJar($filename);
if ($testSaveSessionCookie) {
$this->assertEquals(2, count($cookieJarReloaded));
} else {
$this->assertEquals(1, count($cookieJarReloaded));
}
unlink($filename);
Reference: https://alvinbunk.wordpress.com/2017/04/21/using-cookies-with-phpunit-and-symfony-basic-client/
https://hotexamples.com/examples/goutte/Client/getCookieJar/php-client-getcookiejar-method-examples.html