Cookie.php 12 KB

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