Cookie.php 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  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\BrowserKit;
  11. /**
  12. * Cookie represents an HTTP cookie.
  13. *
  14. * @author Fabien Potencier <fabien@symfony.com>
  15. */
  16. class Cookie
  17. {
  18. /**
  19. * Handles dates as defined by RFC 2616 section 3.3.1, and also some other
  20. * non-standard, but common formats.
  21. */
  22. private static $dateFormats = [
  23. 'D, d M Y H:i:s T',
  24. 'D, d-M-y H:i:s T',
  25. 'D, d-M-Y H:i:s T',
  26. 'D, d-m-y H:i:s T',
  27. 'D, d-m-Y H:i:s T',
  28. 'D M j G:i:s Y',
  29. 'D M d H:i:s Y T',
  30. ];
  31. protected $name;
  32. protected $value;
  33. protected $expires;
  34. protected $path;
  35. protected $domain;
  36. protected $secure;
  37. protected $httponly;
  38. protected $rawValue;
  39. private $samesite;
  40. /**
  41. * Sets a cookie.
  42. *
  43. * @param string $name The cookie name
  44. * @param string $value The value of the cookie
  45. * @param string|null $expires The time the cookie expires
  46. * @param string|null $path The path on the server in which the cookie will be available on
  47. * @param string $domain The domain that the cookie is available
  48. * @param bool $secure Indicates that the cookie should only be transmitted over a secure HTTPS connection from the client
  49. * @param bool $httponly The cookie httponly flag
  50. * @param bool $encodedValue Whether the value is encoded or not
  51. * @param string|null $samesite The cookie samesite attribute
  52. */
  53. public function __construct(string $name, ?string $value, string $expires = null, string $path = null, string $domain = '', bool $secure = false, bool $httponly = true, bool $encodedValue = false, string $samesite = null)
  54. {
  55. if ($encodedValue) {
  56. $this->value = urldecode($value);
  57. $this->rawValue = $value;
  58. } else {
  59. $this->value = $value;
  60. $this->rawValue = rawurlencode($value);
  61. }
  62. $this->name = $name;
  63. $this->path = empty($path) ? '/' : $path;
  64. $this->domain = $domain;
  65. $this->secure = $secure;
  66. $this->httponly = $httponly;
  67. $this->samesite = $samesite;
  68. if (null !== $expires) {
  69. $timestampAsDateTime = \DateTime::createFromFormat('U', $expires);
  70. if (false === $timestampAsDateTime) {
  71. throw new \UnexpectedValueException(sprintf('The cookie expiration time "%s" is not valid.', $expires));
  72. }
  73. $this->expires = $timestampAsDateTime->format('U');
  74. }
  75. }
  76. /**
  77. * Returns the HTTP representation of the Cookie.
  78. */
  79. public function __toString()
  80. {
  81. $cookie = sprintf('%s=%s', $this->name, $this->rawValue);
  82. if (null !== $this->expires) {
  83. $dateTime = \DateTime::createFromFormat('U', $this->expires, new \DateTimeZone('GMT'));
  84. $cookie .= '; expires='.str_replace('+0000', '', $dateTime->format(self::$dateFormats[0]));
  85. }
  86. if ('' !== $this->domain) {
  87. $cookie .= '; domain='.$this->domain;
  88. }
  89. if ($this->path) {
  90. $cookie .= '; path='.$this->path;
  91. }
  92. if ($this->secure) {
  93. $cookie .= '; secure';
  94. }
  95. if ($this->httponly) {
  96. $cookie .= '; httponly';
  97. }
  98. if (null !== $this->samesite) {
  99. $cookie .= '; samesite='.$this->samesite;
  100. }
  101. return $cookie;
  102. }
  103. /**
  104. * Creates a Cookie instance from a Set-Cookie header value.
  105. *
  106. * @param string $cookie A Set-Cookie header value
  107. * @param string|null $url The base URL
  108. *
  109. * @return static
  110. *
  111. * @throws \InvalidArgumentException
  112. */
  113. public static function fromString($cookie, $url = null)
  114. {
  115. $parts = explode(';', $cookie);
  116. if (false === strpos($parts[0], '=')) {
  117. throw new \InvalidArgumentException(sprintf('The cookie string "%s" is not valid.', $parts[0]));
  118. }
  119. list($name, $value) = explode('=', array_shift($parts), 2);
  120. $values = [
  121. 'name' => trim($name),
  122. 'value' => trim($value),
  123. 'expires' => null,
  124. 'path' => '/',
  125. 'domain' => '',
  126. 'secure' => false,
  127. 'httponly' => false,
  128. 'passedRawValue' => true,
  129. 'samesite' => null,
  130. ];
  131. if (null !== $url) {
  132. if ((false === $urlParts = parse_url($url)) || !isset($urlParts['host'])) {
  133. throw new \InvalidArgumentException(sprintf('The URL "%s" is not valid.', $url));
  134. }
  135. $values['domain'] = $urlParts['host'];
  136. $values['path'] = isset($urlParts['path']) ? substr($urlParts['path'], 0, strrpos($urlParts['path'], '/')) : '';
  137. }
  138. foreach ($parts as $part) {
  139. $part = trim($part);
  140. if ('secure' === strtolower($part)) {
  141. // Ignore the secure flag if the original URI is not given or is not HTTPS
  142. if (!$url || !isset($urlParts['scheme']) || 'https' != $urlParts['scheme']) {
  143. continue;
  144. }
  145. $values['secure'] = true;
  146. continue;
  147. }
  148. if ('httponly' === strtolower($part)) {
  149. $values['httponly'] = true;
  150. continue;
  151. }
  152. if (2 === \count($elements = explode('=', $part, 2))) {
  153. if ('expires' === strtolower($elements[0])) {
  154. $elements[1] = self::parseDate($elements[1]);
  155. }
  156. $values[strtolower($elements[0])] = $elements[1];
  157. }
  158. }
  159. return new static(
  160. $values['name'],
  161. $values['value'],
  162. $values['expires'],
  163. $values['path'],
  164. $values['domain'],
  165. $values['secure'],
  166. $values['httponly'],
  167. $values['passedRawValue'],
  168. $values['samesite']
  169. );
  170. }
  171. private static function parseDate($dateValue)
  172. {
  173. // trim single quotes around date if present
  174. if (($length = \strlen($dateValue)) > 1 && "'" === $dateValue[0] && "'" === $dateValue[$length - 1]) {
  175. $dateValue = substr($dateValue, 1, -1);
  176. }
  177. foreach (self::$dateFormats as $dateFormat) {
  178. if (false !== $date = \DateTime::createFromFormat($dateFormat, $dateValue, new \DateTimeZone('GMT'))) {
  179. return $date->format('U');
  180. }
  181. }
  182. // attempt a fallback for unusual formatting
  183. if (false !== $date = date_create($dateValue, new \DateTimeZone('GMT'))) {
  184. return $date->format('U');
  185. }
  186. }
  187. /**
  188. * Gets the name of the cookie.
  189. *
  190. * @return string The cookie name
  191. */
  192. public function getName()
  193. {
  194. return $this->name;
  195. }
  196. /**
  197. * Gets the value of the cookie.
  198. *
  199. * @return string The cookie value
  200. */
  201. public function getValue()
  202. {
  203. return $this->value;
  204. }
  205. /**
  206. * Gets the raw value of the cookie.
  207. *
  208. * @return string The cookie value
  209. */
  210. public function getRawValue()
  211. {
  212. return $this->rawValue;
  213. }
  214. /**
  215. * Gets the expires time of the cookie.
  216. *
  217. * @return string|null The cookie expires time
  218. */
  219. public function getExpiresTime()
  220. {
  221. return $this->expires;
  222. }
  223. /**
  224. * Gets the path of the cookie.
  225. *
  226. * @return string The cookie path
  227. */
  228. public function getPath()
  229. {
  230. return $this->path;
  231. }
  232. /**
  233. * Gets the domain of the cookie.
  234. *
  235. * @return string The cookie domain
  236. */
  237. public function getDomain()
  238. {
  239. return $this->domain;
  240. }
  241. /**
  242. * Returns the secure flag of the cookie.
  243. *
  244. * @return bool The cookie secure flag
  245. */
  246. public function isSecure()
  247. {
  248. return $this->secure;
  249. }
  250. /**
  251. * Returns the httponly flag of the cookie.
  252. *
  253. * @return bool The cookie httponly flag
  254. */
  255. public function isHttpOnly()
  256. {
  257. return $this->httponly;
  258. }
  259. /**
  260. * Returns true if the cookie has expired.
  261. *
  262. * @return bool true if the cookie has expired, false otherwise
  263. */
  264. public function isExpired()
  265. {
  266. return null !== $this->expires && 0 != $this->expires && $this->expires < time();
  267. }
  268. /**
  269. * Gets the samesite attribute of the cookie.
  270. *
  271. * @return string|null The cookie samesite attribute
  272. */
  273. public function getSameSite(): ?string
  274. {
  275. return $this->samesite;
  276. }
  277. }