FileCookieJar.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <?php
  2. namespace GuzzleHttp\Cookie;
  3. /**
  4. * Persists non-session cookies using a JSON formatted file
  5. */
  6. class FileCookieJar extends CookieJar
  7. {
  8. /** @var string filename */
  9. private $filename;
  10. /** @var bool Control whether to persist session cookies or not. */
  11. private $storeSessionCookies;
  12. /**
  13. * Create a new FileCookieJar object
  14. *
  15. * @param string $cookieFile File to store the cookie data
  16. * @param bool $storeSessionCookies Set to true to store session cookies
  17. * in the cookie jar.
  18. *
  19. * @throws \RuntimeException if the file cannot be found or created
  20. */
  21. public function __construct($cookieFile, $storeSessionCookies = false)
  22. {
  23. $this->filename = $cookieFile;
  24. $this->storeSessionCookies = $storeSessionCookies;
  25. if (file_exists($cookieFile)) {
  26. $this->load($cookieFile);
  27. }
  28. }
  29. /**
  30. * Saves the file when shutting down
  31. */
  32. public function __destruct()
  33. {
  34. $this->save($this->filename);
  35. }
  36. /**
  37. * Saves the cookies to a file.
  38. *
  39. * @param string $filename File to save
  40. * @throws \RuntimeException if the file cannot be found or created
  41. */
  42. public function save($filename)
  43. {
  44. $json = [];
  45. foreach ($this as $cookie) {
  46. /** @var SetCookie $cookie */
  47. if (CookieJar::shouldPersist($cookie, $this->storeSessionCookies)) {
  48. $json[] = $cookie->toArray();
  49. }
  50. }
  51. $jsonStr = \GuzzleHttp\json_encode($json);
  52. if (false === file_put_contents($filename, $jsonStr)) {
  53. throw new \RuntimeException("Unable to save file {$filename}");
  54. }
  55. }
  56. /**
  57. * Load cookies from a JSON formatted file.
  58. *
  59. * Old cookies are kept unless overwritten by newly loaded ones.
  60. *
  61. * @param string $filename Cookie file to load.
  62. * @throws \RuntimeException if the file cannot be loaded.
  63. */
  64. public function load($filename)
  65. {
  66. $json = file_get_contents($filename);
  67. if (false === $json) {
  68. throw new \RuntimeException("Unable to load file {$filename}");
  69. } elseif ($json === '') {
  70. return;
  71. }
  72. $data = \GuzzleHttp\json_decode($json, true);
  73. if (is_array($data)) {
  74. foreach (json_decode($json, true) as $cookie) {
  75. $this->setCookie(new SetCookie($cookie));
  76. }
  77. } elseif (strlen($data)) {
  78. throw new \RuntimeException("Invalid cookie file: {$filename}");
  79. }
  80. }
  81. }