Cookie.php 7.9 KB

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