Cookie.php 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  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. protected $name;
  19. protected $value;
  20. protected $domain;
  21. protected $expire;
  22. protected $path;
  23. protected $secure;
  24. protected $httpOnly;
  25. private $raw;
  26. private $sameSite;
  27. private $secureDefault = false;
  28. const SAMESITE_LAX = 'lax';
  29. const SAMESITE_STRICT = 'strict';
  30. /**
  31. * Creates cookie from raw header string.
  32. *
  33. * @param string $cookie
  34. * @param bool $decode
  35. *
  36. * @return static
  37. */
  38. public static function fromString($cookie, $decode = false)
  39. {
  40. $data = [
  41. 'expires' => 0,
  42. 'path' => '/',
  43. 'domain' => null,
  44. 'secure' => false,
  45. 'httponly' => false,
  46. 'raw' => !$decode,
  47. 'samesite' => null,
  48. ];
  49. $parts = HeaderUtils::split($cookie, ';=');
  50. $part = array_shift($parts);
  51. $name = $decode ? urldecode($part[0]) : $part[0];
  52. $value = isset($part[1]) ? ($decode ? urldecode($part[1]) : $part[1]) : null;
  53. $data = HeaderUtils::combine($parts) + $data;
  54. if (isset($data['max-age'])) {
  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, $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, $expire = 0, ?string $path = '/', string $domain = null, ?bool $secure = false, bool $httpOnly = true, bool $raw = false, string $sameSite = null)
  77. {
  78. if (9 > \func_num_args()) {
  79. @trigger_error(sprintf('The default value of the "$secure" and "$samesite" arguments of "%s"\'s constructor will respectively change from "false" to "null" and from "null" to "lax" in Symfony 5.0, you should define their values explicitly or use "Cookie::create()" instead.', __METHOD__), E_USER_DEPRECATED);
  80. }
  81. // from PHP source code
  82. if (preg_match("/[=,; \t\r\n\013\014]/", $name)) {
  83. throw new \InvalidArgumentException(sprintf('The cookie name "%s" contains invalid characters.', $name));
  84. }
  85. if (empty($name)) {
  86. throw new \InvalidArgumentException('The cookie name cannot be empty.');
  87. }
  88. // convert expiration time to a Unix timestamp
  89. if ($expire instanceof \DateTimeInterface) {
  90. $expire = $expire->format('U');
  91. } elseif (!is_numeric($expire)) {
  92. $expire = strtotime($expire);
  93. if (false === $expire) {
  94. throw new \InvalidArgumentException('The cookie expiration time is not valid.');
  95. }
  96. }
  97. $this->name = $name;
  98. $this->value = $value;
  99. $this->domain = $domain;
  100. $this->expire = 0 < $expire ? (int) $expire : 0;
  101. $this->path = empty($path) ? '/' : $path;
  102. $this->secure = $secure;
  103. $this->httpOnly = $httpOnly;
  104. $this->raw = $raw;
  105. if ('' === $sameSite) {
  106. $sameSite = null;
  107. } elseif (null !== $sameSite) {
  108. $sameSite = strtolower($sameSite);
  109. }
  110. if (!\in_array($sameSite, [self::SAMESITE_LAX, self::SAMESITE_STRICT, null], true)) {
  111. throw new \InvalidArgumentException('The "sameSite" parameter value is not valid.');
  112. }
  113. $this->sameSite = $sameSite;
  114. }
  115. /**
  116. * Returns the cookie as a string.
  117. *
  118. * @return string The cookie
  119. */
  120. public function __toString()
  121. {
  122. $str = ($this->isRaw() ? $this->getName() : urlencode($this->getName())).'=';
  123. if ('' === (string) $this->getValue()) {
  124. $str .= 'deleted; expires='.gmdate('D, d-M-Y H:i:s T', time() - 31536001).'; Max-Age=0';
  125. } else {
  126. $str .= $this->isRaw() ? $this->getValue() : rawurlencode($this->getValue());
  127. if (0 !== $this->getExpiresTime()) {
  128. $str .= '; expires='.gmdate('D, d-M-Y H:i:s T', $this->getExpiresTime()).'; Max-Age='.$this->getMaxAge();
  129. }
  130. }
  131. if ($this->getPath()) {
  132. $str .= '; path='.$this->getPath();
  133. }
  134. if ($this->getDomain()) {
  135. $str .= '; domain='.$this->getDomain();
  136. }
  137. if (true === $this->isSecure()) {
  138. $str .= '; secure';
  139. }
  140. if (true === $this->isHttpOnly()) {
  141. $str .= '; httponly';
  142. }
  143. if (null !== $this->getSameSite()) {
  144. $str .= '; samesite='.$this->getSameSite();
  145. }
  146. return $str;
  147. }
  148. /**
  149. * Gets the name of the cookie.
  150. *
  151. * @return string
  152. */
  153. public function getName()
  154. {
  155. return $this->name;
  156. }
  157. /**
  158. * Gets the value of the cookie.
  159. *
  160. * @return string|null
  161. */
  162. public function getValue()
  163. {
  164. return $this->value;
  165. }
  166. /**
  167. * Gets the domain that the cookie is available to.
  168. *
  169. * @return string|null
  170. */
  171. public function getDomain()
  172. {
  173. return $this->domain;
  174. }
  175. /**
  176. * Gets the time the cookie expires.
  177. *
  178. * @return int
  179. */
  180. public function getExpiresTime()
  181. {
  182. return $this->expire;
  183. }
  184. /**
  185. * Gets the max-age attribute.
  186. *
  187. * @return int
  188. */
  189. public function getMaxAge()
  190. {
  191. $maxAge = $this->expire - time();
  192. return 0 >= $maxAge ? 0 : $maxAge;
  193. }
  194. /**
  195. * Gets the path on the server in which the cookie will be available on.
  196. *
  197. * @return string
  198. */
  199. public function getPath()
  200. {
  201. return $this->path;
  202. }
  203. /**
  204. * Checks whether the cookie should only be transmitted over a secure HTTPS connection from the client.
  205. *
  206. * @return bool
  207. */
  208. public function isSecure()
  209. {
  210. return $this->secure ?? $this->secureDefault;
  211. }
  212. /**
  213. * Checks whether the cookie will be made accessible only through the HTTP protocol.
  214. *
  215. * @return bool
  216. */
  217. public function isHttpOnly()
  218. {
  219. return $this->httpOnly;
  220. }
  221. /**
  222. * Whether this cookie is about to be cleared.
  223. *
  224. * @return bool
  225. */
  226. public function isCleared()
  227. {
  228. return 0 !== $this->expire && $this->expire < time();
  229. }
  230. /**
  231. * Checks if the cookie value should be sent with no url encoding.
  232. *
  233. * @return bool
  234. */
  235. public function isRaw()
  236. {
  237. return $this->raw;
  238. }
  239. /**
  240. * Gets the SameSite attribute.
  241. *
  242. * @return string|null
  243. */
  244. public function getSameSite()
  245. {
  246. return $this->sameSite;
  247. }
  248. /**
  249. * @param bool $default The default value of the "secure" flag when it is set to null
  250. */
  251. public function setSecureDefault(bool $default): void
  252. {
  253. $this->secureDefault = $default;
  254. }
  255. }