Cookie.php 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  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. // convert expiration time to a Unix timestamp
  87. if ($expire instanceof \DateTimeInterface) {
  88. $expire = $expire->format('U');
  89. } elseif (!is_numeric($expire)) {
  90. $expire = strtotime($expire);
  91. if (false === $expire) {
  92. throw new \InvalidArgumentException('The cookie expiration time is not valid.');
  93. }
  94. }
  95. $this->name = $name;
  96. $this->value = $value;
  97. $this->domain = $domain;
  98. $this->expire = 0 < $expire ? (int) $expire : 0;
  99. $this->path = empty($path) ? '/' : $path;
  100. $this->secure = $secure;
  101. $this->httpOnly = $httpOnly;
  102. $this->raw = $raw;
  103. if ('' === $sameSite) {
  104. $sameSite = null;
  105. } elseif (null !== $sameSite) {
  106. $sameSite = strtolower($sameSite);
  107. }
  108. if (!\in_array($sameSite, [self::SAMESITE_LAX, self::SAMESITE_STRICT, self::SAMESITE_NONE, null], true)) {
  109. throw new \InvalidArgumentException('The "sameSite" parameter value is not valid.');
  110. }
  111. $this->sameSite = $sameSite;
  112. }
  113. /**
  114. * Returns the cookie as a string.
  115. *
  116. * @return string The cookie
  117. */
  118. public function __toString()
  119. {
  120. if ($this->isRaw()) {
  121. $str = $this->getName();
  122. } else {
  123. $str = str_replace(self::$reservedCharsFrom, self::$reservedCharsTo, $this->getName());
  124. }
  125. $str .= '=';
  126. if ('' === (string) $this->getValue()) {
  127. $str .= 'deleted; expires='.gmdate('D, d-M-Y H:i:s T', time() - 31536001).'; Max-Age=0';
  128. } else {
  129. $str .= $this->isRaw() ? $this->getValue() : rawurlencode($this->getValue());
  130. if (0 !== $this->getExpiresTime()) {
  131. $str .= '; expires='.gmdate('D, d-M-Y H:i:s T', $this->getExpiresTime()).'; Max-Age='.$this->getMaxAge();
  132. }
  133. }
  134. if ($this->getPath()) {
  135. $str .= '; path='.$this->getPath();
  136. }
  137. if ($this->getDomain()) {
  138. $str .= '; domain='.$this->getDomain();
  139. }
  140. if (true === $this->isSecure()) {
  141. $str .= '; secure';
  142. }
  143. if (true === $this->isHttpOnly()) {
  144. $str .= '; httponly';
  145. }
  146. if (null !== $this->getSameSite()) {
  147. $str .= '; samesite='.$this->getSameSite();
  148. }
  149. return $str;
  150. }
  151. /**
  152. * Gets the name of the cookie.
  153. *
  154. * @return string
  155. */
  156. public function getName()
  157. {
  158. return $this->name;
  159. }
  160. /**
  161. * Gets the value of the cookie.
  162. *
  163. * @return string|null
  164. */
  165. public function getValue()
  166. {
  167. return $this->value;
  168. }
  169. /**
  170. * Gets the domain that the cookie is available to.
  171. *
  172. * @return string|null
  173. */
  174. public function getDomain()
  175. {
  176. return $this->domain;
  177. }
  178. /**
  179. * Gets the time the cookie expires.
  180. *
  181. * @return int
  182. */
  183. public function getExpiresTime()
  184. {
  185. return $this->expire;
  186. }
  187. /**
  188. * Gets the max-age attribute.
  189. *
  190. * @return int
  191. */
  192. public function getMaxAge()
  193. {
  194. $maxAge = $this->expire - time();
  195. return 0 >= $maxAge ? 0 : $maxAge;
  196. }
  197. /**
  198. * Gets the path on the server in which the cookie will be available on.
  199. *
  200. * @return string
  201. */
  202. public function getPath()
  203. {
  204. return $this->path;
  205. }
  206. /**
  207. * Checks whether the cookie should only be transmitted over a secure HTTPS connection from the client.
  208. *
  209. * @return bool
  210. */
  211. public function isSecure()
  212. {
  213. return $this->secure ?? $this->secureDefault;
  214. }
  215. /**
  216. * Checks whether the cookie will be made accessible only through the HTTP protocol.
  217. *
  218. * @return bool
  219. */
  220. public function isHttpOnly()
  221. {
  222. return $this->httpOnly;
  223. }
  224. /**
  225. * Whether this cookie is about to be cleared.
  226. *
  227. * @return bool
  228. */
  229. public function isCleared()
  230. {
  231. return 0 !== $this->expire && $this->expire < time();
  232. }
  233. /**
  234. * Checks if the cookie value should be sent with no url encoding.
  235. *
  236. * @return bool
  237. */
  238. public function isRaw()
  239. {
  240. return $this->raw;
  241. }
  242. /**
  243. * Gets the SameSite attribute.
  244. *
  245. * @return string|null
  246. */
  247. public function getSameSite()
  248. {
  249. return $this->sameSite;
  250. }
  251. /**
  252. * @param bool $default The default value of the "secure" flag when it is set to null
  253. */
  254. public function setSecureDefault(bool $default): void
  255. {
  256. $this->secureDefault = $default;
  257. }
  258. }