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 const DATE_FORMATS = [
  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. * @return string
  80. */
  81. public function __toString()
  82. {
  83. $cookie = sprintf('%s=%s', $this->name, $this->rawValue);
  84. if (null !== $this->expires) {
  85. $dateTime = \DateTime::createFromFormat('U', $this->expires, new \DateTimeZone('GMT'));
  86. $cookie .= '; expires='.str_replace('+0000', '', $dateTime->format(self::DATE_FORMATS[0]));
  87. }
  88. if ('' !== $this->domain) {
  89. $cookie .= '; domain='.$this->domain;
  90. }
  91. if ($this->path) {
  92. $cookie .= '; path='.$this->path;
  93. }
  94. if ($this->secure) {
  95. $cookie .= '; secure';
  96. }
  97. if ($this->httponly) {
  98. $cookie .= '; httponly';
  99. }
  100. if (null !== $this->samesite) {
  101. $cookie .= '; samesite='.$this->samesite;
  102. }
  103. return $cookie;
  104. }
  105. /**
  106. * Creates a Cookie instance from a Set-Cookie header value.
  107. *
  108. * @return static
  109. *
  110. * @throws \InvalidArgumentException
  111. */
  112. public static function fromString(string $cookie, string $url = null)
  113. {
  114. $parts = explode(';', $cookie);
  115. if (false === strpos($parts[0], '=')) {
  116. throw new \InvalidArgumentException(sprintf('The cookie string "%s" is not valid.', $parts[0]));
  117. }
  118. [$name, $value] = explode('=', array_shift($parts), 2);
  119. $values = [
  120. 'name' => trim($name),
  121. 'value' => trim($value),
  122. 'expires' => null,
  123. 'path' => '/',
  124. 'domain' => '',
  125. 'secure' => false,
  126. 'httponly' => false,
  127. 'passedRawValue' => true,
  128. 'samesite' => null,
  129. ];
  130. if (null !== $url) {
  131. if ((false === $urlParts = parse_url($url)) || !isset($urlParts['host'])) {
  132. throw new \InvalidArgumentException(sprintf('The URL "%s" is not valid.', $url));
  133. }
  134. $values['domain'] = $urlParts['host'];
  135. $values['path'] = isset($urlParts['path']) ? substr($urlParts['path'], 0, strrpos($urlParts['path'], '/')) : '';
  136. }
  137. foreach ($parts as $part) {
  138. $part = trim($part);
  139. if ('secure' === strtolower($part)) {
  140. // Ignore the secure flag if the original URI is not given or is not HTTPS
  141. if (!$url || !isset($urlParts['scheme']) || 'https' != $urlParts['scheme']) {
  142. continue;
  143. }
  144. $values['secure'] = true;
  145. continue;
  146. }
  147. if ('httponly' === strtolower($part)) {
  148. $values['httponly'] = true;
  149. continue;
  150. }
  151. if (2 === \count($elements = explode('=', $part, 2))) {
  152. if ('expires' === strtolower($elements[0])) {
  153. $elements[1] = self::parseDate($elements[1]);
  154. }
  155. $values[strtolower($elements[0])] = $elements[1];
  156. }
  157. }
  158. return new static(
  159. $values['name'],
  160. $values['value'],
  161. $values['expires'],
  162. $values['path'],
  163. $values['domain'],
  164. $values['secure'],
  165. $values['httponly'],
  166. $values['passedRawValue'],
  167. $values['samesite']
  168. );
  169. }
  170. private static function parseDate(string $dateValue): ?string
  171. {
  172. // trim single quotes around date if present
  173. if (($length = \strlen($dateValue)) > 1 && "'" === $dateValue[0] && "'" === $dateValue[$length - 1]) {
  174. $dateValue = substr($dateValue, 1, -1);
  175. }
  176. foreach (self::DATE_FORMATS as $dateFormat) {
  177. if (false !== $date = \DateTime::createFromFormat($dateFormat, $dateValue, new \DateTimeZone('GMT'))) {
  178. return $date->format('U');
  179. }
  180. }
  181. // attempt a fallback for unusual formatting
  182. if (false !== $date = date_create($dateValue, new \DateTimeZone('GMT'))) {
  183. return $date->format('U');
  184. }
  185. return null;
  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. }