Cookie.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\HttpFoundation;
  11. /**
  12. * Represents a cookie.
  13. *
  14. * @author Johannes M. Schmitt <schmittjoh@gmail.com>
  15. */
  16. class Cookie
  17. {
  18. const SAMESITE_NONE = 'none';
  19. const SAMESITE_LAX = 'lax';
  20. const SAMESITE_STRICT = 'strict';
  21. protected $name;
  22. protected $value;
  23. protected $domain;
  24. protected $expire;
  25. protected $path;
  26. protected $secure;
  27. protected $httpOnly;
  28. private $raw;
  29. private $sameSite;
  30. private $secureDefault = false;
  31. private static $reservedCharsList = "=,; \t\r\n\v\f";
  32. private static $reservedCharsFrom = ['=', ',', ';', ' ', "\t", "\r", "\n", "\v", "\f"];
  33. private static $reservedCharsTo = ['%3D', '%2C', '%3B', '%20', '%09', '%0D', '%0A', '%0B', '%0C'];
  34. /**
  35. * Creates cookie from raw header string.
  36. *
  37. * @return static
  38. */
  39. public static function fromString(string $cookie, bool $decode = false)
  40. {
  41. $data = [
  42. 'expires' => 0,
  43. 'path' => '/',
  44. 'domain' => null,
  45. 'secure' => false,
  46. 'httponly' => false,
  47. 'raw' => !$decode,
  48. 'samesite' => null,
  49. ];
  50. $parts = HeaderUtils::split($cookie, ';=');
  51. $part = array_shift($parts);
  52. $name = $decode ? urldecode($part[0]) : $part[0];
  53. $value = isset($part[1]) ? ($decode ? urldecode($part[1]) : $part[1]) : null;
  54. $data = HeaderUtils::combine($parts) + $data;
  55. if (isset($data['max-age'])) {
  56. $data['expires'] = time() + (int) $data['max-age'];
  57. }
  58. return new static($name, $value, $data['expires'], $data['path'], $data['domain'], $data['secure'], $data['httponly'], $data['raw'], $data['samesite']);
  59. }
  60. public static function create(string $name, string $value = null, $expire = 0, ?string $path = '/', string $domain = null, bool $secure = null, bool $httpOnly = true, bool $raw = false, ?string $sameSite = self::SAMESITE_LAX): self
  61. {
  62. return new self($name, $value, $expire, $path, $domain, $secure, $httpOnly, $raw, $sameSite);
  63. }
  64. /**
  65. * @param string $name The name of the cookie
  66. * @param string|null $value The value of the cookie
  67. * @param int|string|\DateTimeInterface $expire The time the cookie expires
  68. * @param string $path The path on the server in which the cookie will be available on
  69. * @param string|null $domain The domain that the cookie is available to
  70. * @param bool|null $secure Whether the client should send back the cookie only over HTTPS or null to auto-enable this when the request is already using HTTPS
  71. * @param bool $httpOnly Whether the cookie will be made accessible only through the HTTP protocol
  72. * @param bool $raw Whether the cookie value should be sent with no url encoding
  73. * @param string|null $sameSite Whether the cookie will be available for cross-site requests
  74. *
  75. * @throws \InvalidArgumentException
  76. */
  77. public function __construct(string $name, string $value = null, $expire = 0, ?string $path = '/', string $domain = null, bool $secure = null, bool $httpOnly = true, bool $raw = false, ?string $sameSite = 'lax')
  78. {
  79. // from PHP source code
  80. if ($raw && false !== strpbrk($name, self::$reservedCharsList)) {
  81. throw new \InvalidArgumentException(sprintf('The cookie name "%s" contains invalid characters.', $name));
  82. }
  83. if (empty($name)) {
  84. throw new \InvalidArgumentException('The cookie name cannot be empty.');
  85. }
  86. $this->name = $name;
  87. $this->value = $value;
  88. $this->domain = $domain;
  89. $this->expire = $this->withExpires($expire)->expire;
  90. $this->path = empty($path) ? '/' : $path;
  91. $this->secure = $secure;
  92. $this->httpOnly = $httpOnly;
  93. $this->raw = $raw;
  94. $this->sameSite = $this->withSameSite($sameSite)->sameSite;
  95. }
  96. /**
  97. * Creates a cookie copy with a new value.
  98. *
  99. * @return static
  100. */
  101. public function withValue(?string $value): self
  102. {
  103. $cookie = clone $this;
  104. $cookie->value = $value;
  105. return $cookie;
  106. }
  107. /**
  108. * Creates a cookie copy with a new domain that the cookie is available to.
  109. *
  110. * @return static
  111. */
  112. public function withDomain(?string $domain): self
  113. {
  114. $cookie = clone $this;
  115. $cookie->domain = $domain;
  116. return $cookie;
  117. }
  118. /**
  119. * Creates a cookie copy with a new time the cookie expires.
  120. *
  121. * @param int|string|\DateTimeInterface $expire
  122. *
  123. * @return static
  124. */
  125. public function withExpires($expire = 0): self
  126. {
  127. // convert expiration time to a Unix timestamp
  128. if ($expire instanceof \DateTimeInterface) {
  129. $expire = $expire->format('U');
  130. } elseif (!is_numeric($expire)) {
  131. $expire = strtotime($expire);
  132. if (false === $expire) {
  133. throw new \InvalidArgumentException('The cookie expiration time is not valid.');
  134. }
  135. }
  136. $cookie = clone $this;
  137. $cookie->expire = 0 < $expire ? (int) $expire : 0;
  138. return $cookie;
  139. }
  140. /**
  141. * Creates a cookie copy with a new path on the server in which the cookie will be available on.
  142. *
  143. * @return static
  144. */
  145. public function withPath(string $path): self
  146. {
  147. $cookie = clone $this;
  148. $cookie->path = '' === $path ? '/' : $path;
  149. return $cookie;
  150. }
  151. /**
  152. * Creates a cookie copy that only be transmitted over a secure HTTPS connection from the client.
  153. *
  154. * @return static
  155. */
  156. public function withSecure(bool $secure = true): self
  157. {
  158. $cookie = clone $this;
  159. $cookie->secure = $secure;
  160. return $cookie;
  161. }
  162. /**
  163. * Creates a cookie copy that be accessible only through the HTTP protocol.
  164. *
  165. * @return static
  166. */
  167. public function withHttpOnly(bool $httpOnly = true): self
  168. {
  169. $cookie = clone $this;
  170. $cookie->httpOnly = $httpOnly;
  171. return $cookie;
  172. }
  173. /**
  174. * Creates a cookie copy that uses no url encoding.
  175. *
  176. * @return static
  177. */
  178. public function withRaw(bool $raw = true): self
  179. {
  180. if ($raw && false !== strpbrk($this->name, self::$reservedCharsList)) {
  181. throw new \InvalidArgumentException(sprintf('The cookie name "%s" contains invalid characters.', $this->name));
  182. }
  183. $cookie = clone $this;
  184. $cookie->raw = $raw;
  185. return $cookie;
  186. }
  187. /**
  188. * Creates a cookie copy with SameSite attribute.
  189. *
  190. * @return static
  191. */
  192. public function withSameSite(?string $sameSite): self
  193. {
  194. if ('' === $sameSite) {
  195. $sameSite = null;
  196. } elseif (null !== $sameSite) {
  197. $sameSite = strtolower($sameSite);
  198. }
  199. if (!\in_array($sameSite, [self::SAMESITE_LAX, self::SAMESITE_STRICT, self::SAMESITE_NONE, null], true)) {
  200. throw new \InvalidArgumentException('The "sameSite" parameter value is not valid.');
  201. }
  202. $cookie = clone $this;
  203. $cookie->sameSite = $sameSite;
  204. return $cookie;
  205. }
  206. /**
  207. * Returns the cookie as a string.
  208. *
  209. * @return string The cookie
  210. */
  211. public function __toString()
  212. {
  213. if ($this->isRaw()) {
  214. $str = $this->getName();
  215. } else {
  216. $str = str_replace(self::$reservedCharsFrom, self::$reservedCharsTo, $this->getName());
  217. }
  218. $str .= '=';
  219. if ('' === (string) $this->getValue()) {
  220. $str .= 'deleted; expires='.gmdate('D, d-M-Y H:i:s T', time() - 31536001).'; Max-Age=0';
  221. } else {
  222. $str .= $this->isRaw() ? $this->getValue() : rawurlencode($this->getValue());
  223. if (0 !== $this->getExpiresTime()) {
  224. $str .= '; expires='.gmdate('D, d-M-Y H:i:s T', $this->getExpiresTime()).'; Max-Age='.$this->getMaxAge();
  225. }
  226. }
  227. if ($this->getPath()) {
  228. $str .= '; path='.$this->getPath();
  229. }
  230. if ($this->getDomain()) {
  231. $str .= '; domain='.$this->getDomain();
  232. }
  233. if (true === $this->isSecure()) {
  234. $str .= '; secure';
  235. }
  236. if (true === $this->isHttpOnly()) {
  237. $str .= '; httponly';
  238. }
  239. if (null !== $this->getSameSite()) {
  240. $str .= '; samesite='.$this->getSameSite();
  241. }
  242. return $str;
  243. }
  244. /**
  245. * Gets the name of the cookie.
  246. *
  247. * @return string
  248. */
  249. public function getName()
  250. {
  251. return $this->name;
  252. }
  253. /**
  254. * Gets the value of the cookie.
  255. *
  256. * @return string|null
  257. */
  258. public function getValue()
  259. {
  260. return $this->value;
  261. }
  262. /**
  263. * Gets the domain that the cookie is available to.
  264. *
  265. * @return string|null
  266. */
  267. public function getDomain()
  268. {
  269. return $this->domain;
  270. }
  271. /**
  272. * Gets the time the cookie expires.
  273. *
  274. * @return int
  275. */
  276. public function getExpiresTime()
  277. {
  278. return $this->expire;
  279. }
  280. /**
  281. * Gets the max-age attribute.
  282. *
  283. * @return int
  284. */
  285. public function getMaxAge()
  286. {
  287. $maxAge = $this->expire - time();
  288. return 0 >= $maxAge ? 0 : $maxAge;
  289. }
  290. /**
  291. * Gets the path on the server in which the cookie will be available on.
  292. *
  293. * @return string
  294. */
  295. public function getPath()
  296. {
  297. return $this->path;
  298. }
  299. /**
  300. * Checks whether the cookie should only be transmitted over a secure HTTPS connection from the client.
  301. *
  302. * @return bool
  303. */
  304. public function isSecure()
  305. {
  306. return $this->secure ?? $this->secureDefault;
  307. }
  308. /**
  309. * Checks whether the cookie will be made accessible only through the HTTP protocol.
  310. *
  311. * @return bool
  312. */
  313. public function isHttpOnly()
  314. {
  315. return $this->httpOnly;
  316. }
  317. /**
  318. * Whether this cookie is about to be cleared.
  319. *
  320. * @return bool
  321. */
  322. public function isCleared()
  323. {
  324. return 0 !== $this->expire && $this->expire < time();
  325. }
  326. /**
  327. * Checks if the cookie value should be sent with no url encoding.
  328. *
  329. * @return bool
  330. */
  331. public function isRaw()
  332. {
  333. return $this->raw;
  334. }
  335. /**
  336. * Gets the SameSite attribute.
  337. *
  338. * @return string|null
  339. */
  340. public function getSameSite()
  341. {
  342. return $this->sameSite;
  343. }
  344. /**
  345. * @param bool $default The default value of the "secure" flag when it is set to null
  346. */
  347. public function setSecureDefault(bool $default): void
  348. {
  349. $this->secureDefault = $default;
  350. }
  351. }