Setting up cookies for Guzzle CookieJar

帅比萌擦擦* 提交于 2019-12-05 05:15:59
DrDamnit

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 
]);

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!