FileCookieJar.php 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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. parent::__construct();
  24. $this->filename = $cookieFile;
  25. $this->storeSessionCookies = $storeSessionCookies;
  26. if (file_exists($cookieFile)) {
  27. $this->load($cookieFile);
  28. }
  29. }
  30. /**
  31. * Saves the file when shutting down
  32. */
  33. public function __destruct()
  34. {
  35. $this->save($this->filename);
  36. }
  37. /**
  38. * Saves the cookies to a file.
  39. *
  40. * @param string $filename File to save
  41. * @throws \RuntimeException if the file cannot be found or created
  42. */
  43. public function save($filename)
  44. {
  45. $json = [];
  46. foreach ($this as $cookie) {
  47. /** @var SetCookie $cookie */
  48. if (CookieJar::shouldPersist($cookie, $this->storeSessionCookies)) {
  49. $json[] = $cookie->toArray();
  50. }
  51. }
  52. $jsonStr = \GuzzleHttp\json_encode($json);
  53. if (false === file_put_contents($filename, $jsonStr, LOCK_EX)) {
  54. throw new \RuntimeException("Unable to save file {$filename}");
  55. }
  56. }
  57. /**
  58. * Load cookies from a JSON formatted file.
  59. *
  60. * Old cookies are kept unless overwritten by newly loaded ones.
  61. *
  62. * @param string $filename Cookie file to load.
  63. * @throws \RuntimeException if the file cannot be loaded.
  64. */
  65. public function load($filename)
  66. {
  67. $json = file_get_contents($filename);
  68. if (false === $json) {
  69. throw new \RuntimeException("Unable to load file {$filename}");
  70. } elseif ($json === '') {
  71. return;
  72. }
  73. $data = \GuzzleHttp\json_decode($json, true);
  74. if (is_array($data)) {
  75. foreach (json_decode($json, true) as $cookie) {
  76. $this->setCookie(new SetCookie($cookie));
  77. }
  78. } elseif (strlen($data)) {
  79. throw new \RuntimeException("Invalid cookie file: {$filename}");
  80. }
  81. }
  82. }