Cookie.php 7.9 KB

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