Cookie.php 7.3KB

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