Cookie.php 11 KB

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