2 namespace GuzzleHttp\Cookie;
5 * Persists non-session cookies using a JSON formatted file
7 class FileCookieJar extends CookieJar
9 /** @var string filename */
12 /** @var bool Control whether to persist session cookies or not. */
13 private $storeSessionCookies;
16 * Create a new FileCookieJar object
18 * @param string $cookieFile File to store the cookie data
19 * @param bool $storeSessionCookies Set to true to store session cookies
22 * @throws \RuntimeException if the file cannot be found or created
24 public function __construct($cookieFile, $storeSessionCookies = false)
26 $this->filename = $cookieFile;
27 $this->storeSessionCookies = $storeSessionCookies;
29 if (file_exists($cookieFile)) {
30 $this->load($cookieFile);
35 * Saves the file when shutting down
37 public function __destruct()
39 $this->save($this->filename);
43 * Saves the cookies to a file.
45 * @param string $filename File to save
46 * @throws \RuntimeException if the file cannot be found or created
48 public function save($filename)
51 foreach ($this as $cookie) {
52 /** @var SetCookie $cookie */
53 if (CookieJar::shouldPersist($cookie, $this->storeSessionCookies)) {
54 $json[] = $cookie->toArray();
58 $jsonStr = \GuzzleHttp\json_encode($json);
59 if (false === file_put_contents($filename, $jsonStr)) {
60 throw new \RuntimeException("Unable to save file {$filename}");
65 * Load cookies from a JSON formatted file.
67 * Old cookies are kept unless overwritten by newly loaded ones.
69 * @param string $filename Cookie file to load.
70 * @throws \RuntimeException if the file cannot be loaded.
72 public function load($filename)
74 $json = file_get_contents($filename);
75 if (false === $json) {
76 throw new \RuntimeException("Unable to load file {$filename}");
77 } elseif ($json === '') {
81 $data = \GuzzleHttp\json_decode($json, true);
82 if (is_array($data)) {
83 foreach (json_decode($json, true) as $cookie) {
84 $this->setCookie(new SetCookie($cookie));
86 } elseif (strlen($data)) {
87 throw new \RuntimeException("Invalid cookie file: {$filename}");