Cookie.php 12 KB

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