Cookie.php 7.8 KB

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