2 namespace GuzzleHttp\Cookie;
5 * Persists cookies in the client session
7 class SessionCookieJar extends CookieJar
9 /** @var string session key */
12 /** @var bool Control whether to persist session cookies or not. */
13 private $storeSessionCookies;
16 * Create a new SessionCookieJar object
18 * @param string $sessionKey Session key name to store the cookie
20 * @param bool $storeSessionCookies Set to true to store session cookies
23 public function __construct($sessionKey, $storeSessionCookies = false)
25 $this->sessionKey = $sessionKey;
26 $this->storeSessionCookies = $storeSessionCookies;
31 * Saves cookies to session when shutting down
33 public function __destruct()
39 * Save cookies to the client session
41 public function save()
44 foreach ($this as $cookie) {
45 /** @var SetCookie $cookie */
46 if (CookieJar::shouldPersist($cookie, $this->storeSessionCookies)) {
47 $json[] = $cookie->toArray();
51 $_SESSION[$this->sessionKey] = json_encode($json);
55 * Load the contents of the client session into the data array
57 protected function load()
59 if (!isset($_SESSION[$this->sessionKey])) {
62 $data = json_decode($_SESSION[$this->sessionKey], true);
63 if (is_array($data)) {
64 foreach ($data as $cookie) {
65 $this->setCookie(new SetCookie($cookie));
67 } elseif (strlen($data)) {
68 throw new \RuntimeException("Invalid cookie data");