SessionCookieJar.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. <?php
  2. namespace GuzzleHttp\Cookie;
  3. /**
  4. * Persists cookies in the client session
  5. */
  6. class SessionCookieJar extends CookieJar
  7. {
  8. /** @var string session key */
  9. private $sessionKey;
  10. /** @var bool Control whether to persist session cookies or not. */
  11. private $storeSessionCookies;
  12. /**
  13. * Create a new SessionCookieJar object
  14. *
  15. * @param string $sessionKey Session key name to store the cookie
  16. * data in session
  17. * @param bool $storeSessionCookies Set to true to store session cookies
  18. * in the cookie jar.
  19. */
  20. public function __construct($sessionKey, $storeSessionCookies = false)
  21. {
  22. $this->sessionKey = $sessionKey;
  23. $this->storeSessionCookies = $storeSessionCookies;
  24. $this->load();
  25. }
  26. /**
  27. * Saves cookies to session when shutting down
  28. */
  29. public function __destruct()
  30. {
  31. $this->save();
  32. }
  33. /**
  34. * Save cookies to the client session
  35. */
  36. public function save()
  37. {
  38. $json = [];
  39. foreach ($this as $cookie) {
  40. /** @var SetCookie $cookie */
  41. if (CookieJar::shouldPersist($cookie, $this->storeSessionCookies)) {
  42. $json[] = $cookie->toArray();
  43. }
  44. }
  45. $_SESSION[$this->sessionKey] = json_encode($json);
  46. }
  47. /**
  48. * Load the contents of the client session into the data array
  49. */
  50. protected function load()
  51. {
  52. if (!isset($_SESSION[$this->sessionKey])) {
  53. return;
  54. }
  55. $data = json_decode($_SESSION[$this->sessionKey], true);
  56. if (is_array($data)) {
  57. foreach ($data as $cookie) {
  58. $this->setCookie(new SetCookie($cookie));
  59. }
  60. } elseif (strlen($data)) {
  61. throw new \RuntimeException("Invalid cookie data");
  62. }
  63. }
  64. }