SetCookie.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  1. <?php
  2. namespace GuzzleHttp\Cookie;
  3. /**
  4. * Set-Cookie object
  5. */
  6. class SetCookie
  7. {
  8. /**
  9. * @var array
  10. */
  11. private static $defaults = [
  12. 'Name' => null,
  13. 'Value' => null,
  14. 'Domain' => null,
  15. 'Path' => '/',
  16. 'Max-Age' => null,
  17. 'Expires' => null,
  18. 'Secure' => false,
  19. 'Discard' => false,
  20. 'HttpOnly' => false,
  21. ];
  22. /**
  23. * @var array Cookie data
  24. */
  25. private $data;
  26. /**
  27. * Create a new SetCookie object from a string.
  28. *
  29. * @param string $cookie Set-Cookie header string
  30. */
  31. public static function fromString(string $cookie): self
  32. {
  33. // Create the default return array
  34. $data = self::$defaults;
  35. // Explode the cookie string using a series of semicolons
  36. $pieces = \array_filter(\array_map('trim', \explode(';', $cookie)));
  37. // The name of the cookie (first kvp) must exist and include an equal sign.
  38. if (!isset($pieces[0]) || \strpos($pieces[0], '=') === false) {
  39. return new self($data);
  40. }
  41. // Add the cookie pieces into the parsed data array
  42. foreach ($pieces as $part) {
  43. $cookieParts = \explode('=', $part, 2);
  44. $key = \trim($cookieParts[0]);
  45. $value = isset($cookieParts[1])
  46. ? \trim($cookieParts[1], " \n\r\t\0\x0B")
  47. : true;
  48. // Only check for non-cookies when cookies have been found
  49. if (!isset($data['Name'])) {
  50. $data['Name'] = $key;
  51. $data['Value'] = $value;
  52. } else {
  53. foreach (\array_keys(self::$defaults) as $search) {
  54. if (!\strcasecmp($search, $key)) {
  55. if ($search === 'Max-Age') {
  56. if (is_numeric($value)) {
  57. $data[$search] = (int) $value;
  58. }
  59. } else {
  60. $data[$search] = $value;
  61. }
  62. continue 2;
  63. }
  64. }
  65. $data[$key] = $value;
  66. }
  67. }
  68. return new self($data);
  69. }
  70. /**
  71. * @param array $data Array of cookie data provided by a Cookie parser
  72. */
  73. public function __construct(array $data = [])
  74. {
  75. $this->data = self::$defaults;
  76. if (isset($data['Name'])) {
  77. $this->setName($data['Name']);
  78. }
  79. if (isset($data['Value'])) {
  80. $this->setValue($data['Value']);
  81. }
  82. if (isset($data['Domain'])) {
  83. $this->setDomain($data['Domain']);
  84. }
  85. if (isset($data['Path'])) {
  86. $this->setPath($data['Path']);
  87. }
  88. if (isset($data['Max-Age'])) {
  89. $this->setMaxAge($data['Max-Age']);
  90. }
  91. if (isset($data['Expires'])) {
  92. $this->setExpires($data['Expires']);
  93. }
  94. if (isset($data['Secure'])) {
  95. $this->setSecure($data['Secure']);
  96. }
  97. if (isset($data['Discard'])) {
  98. $this->setDiscard($data['Discard']);
  99. }
  100. if (isset($data['HttpOnly'])) {
  101. $this->setHttpOnly($data['HttpOnly']);
  102. }
  103. // Set the remaining values that don't have extra validation logic
  104. foreach (array_diff(array_keys($data), array_keys(self::$defaults)) as $key) {
  105. $this->data[$key] = $data[$key];
  106. }
  107. // Extract the Expires value and turn it into a UNIX timestamp if needed
  108. if (!$this->getExpires() && $this->getMaxAge()) {
  109. // Calculate the Expires date
  110. $this->setExpires(\time() + $this->getMaxAge());
  111. } elseif (null !== ($expires = $this->getExpires()) && !\is_numeric($expires)) {
  112. $this->setExpires($expires);
  113. }
  114. }
  115. public function __toString()
  116. {
  117. $str = $this->data['Name'].'='.($this->data['Value'] ?? '').'; ';
  118. foreach ($this->data as $k => $v) {
  119. if ($k !== 'Name' && $k !== 'Value' && $v !== null && $v !== false) {
  120. if ($k === 'Expires') {
  121. $str .= 'Expires='.\gmdate('D, d M Y H:i:s \G\M\T', $v).'; ';
  122. } else {
  123. $str .= ($v === true ? $k : "{$k}={$v}").'; ';
  124. }
  125. }
  126. }
  127. return \rtrim($str, '; ');
  128. }
  129. public function toArray(): array
  130. {
  131. return $this->data;
  132. }
  133. /**
  134. * Get the cookie name.
  135. *
  136. * @return string
  137. */
  138. public function getName()
  139. {
  140. return $this->data['Name'];
  141. }
  142. /**
  143. * Set the cookie name.
  144. *
  145. * @param string $name Cookie name
  146. */
  147. public function setName($name): void
  148. {
  149. if (!is_string($name)) {
  150. trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a string to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__);
  151. }
  152. $this->data['Name'] = (string) $name;
  153. }
  154. /**
  155. * Get the cookie value.
  156. *
  157. * @return string|null
  158. */
  159. public function getValue()
  160. {
  161. return $this->data['Value'];
  162. }
  163. /**
  164. * Set the cookie value.
  165. *
  166. * @param string $value Cookie value
  167. */
  168. public function setValue($value): void
  169. {
  170. if (!is_string($value)) {
  171. trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a string to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__);
  172. }
  173. $this->data['Value'] = (string) $value;
  174. }
  175. /**
  176. * Get the domain.
  177. *
  178. * @return string|null
  179. */
  180. public function getDomain()
  181. {
  182. return $this->data['Domain'];
  183. }
  184. /**
  185. * Set the domain of the cookie.
  186. *
  187. * @param string|null $domain
  188. */
  189. public function setDomain($domain): void
  190. {
  191. if (!is_string($domain) && null !== $domain) {
  192. trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a string or null to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__);
  193. }
  194. $this->data['Domain'] = null === $domain ? null : (string) $domain;
  195. }
  196. /**
  197. * Get the path.
  198. *
  199. * @return string
  200. */
  201. public function getPath()
  202. {
  203. return $this->data['Path'];
  204. }
  205. /**
  206. * Set the path of the cookie.
  207. *
  208. * @param string $path Path of the cookie
  209. */
  210. public function setPath($path): void
  211. {
  212. if (!is_string($path)) {
  213. trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a string to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__);
  214. }
  215. $this->data['Path'] = (string) $path;
  216. }
  217. /**
  218. * Maximum lifetime of the cookie in seconds.
  219. *
  220. * @return int|null
  221. */
  222. public function getMaxAge()
  223. {
  224. return null === $this->data['Max-Age'] ? null : (int) $this->data['Max-Age'];
  225. }
  226. /**
  227. * Set the max-age of the cookie.
  228. *
  229. * @param int|null $maxAge Max age of the cookie in seconds
  230. */
  231. public function setMaxAge($maxAge): void
  232. {
  233. if (!is_int($maxAge) && null !== $maxAge) {
  234. trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing an int or null to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__);
  235. }
  236. $this->data['Max-Age'] = $maxAge === null ? null : (int) $maxAge;
  237. }
  238. /**
  239. * The UNIX timestamp when the cookie Expires.
  240. *
  241. * @return string|int|null
  242. */
  243. public function getExpires()
  244. {
  245. return $this->data['Expires'];
  246. }
  247. /**
  248. * Set the unix timestamp for which the cookie will expire.
  249. *
  250. * @param int|string|null $timestamp Unix timestamp or any English textual datetime description.
  251. */
  252. public function setExpires($timestamp): void
  253. {
  254. if (!is_int($timestamp) && !is_string($timestamp) && null !== $timestamp) {
  255. trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing an int, string or null to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__);
  256. }
  257. $this->data['Expires'] = null === $timestamp ? null : (\is_numeric($timestamp) ? (int) $timestamp : \strtotime((string) $timestamp));
  258. }
  259. /**
  260. * Get whether or not this is a secure cookie.
  261. *
  262. * @return bool
  263. */
  264. public function getSecure()
  265. {
  266. return $this->data['Secure'];
  267. }
  268. /**
  269. * Set whether or not the cookie is secure.
  270. *
  271. * @param bool $secure Set to true or false if secure
  272. */
  273. public function setSecure($secure): void
  274. {
  275. if (!is_bool($secure)) {
  276. trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a bool to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__);
  277. }
  278. $this->data['Secure'] = (bool) $secure;
  279. }
  280. /**
  281. * Get whether or not this is a session cookie.
  282. *
  283. * @return bool|null
  284. */
  285. public function getDiscard()
  286. {
  287. return $this->data['Discard'];
  288. }
  289. /**
  290. * Set whether or not this is a session cookie.
  291. *
  292. * @param bool $discard Set to true or false if this is a session cookie
  293. */
  294. public function setDiscard($discard): void
  295. {
  296. if (!is_bool($discard)) {
  297. trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a bool to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__);
  298. }
  299. $this->data['Discard'] = (bool) $discard;
  300. }
  301. /**
  302. * Get whether or not this is an HTTP only cookie.
  303. *
  304. * @return bool
  305. */
  306. public function getHttpOnly()
  307. {
  308. return $this->data['HttpOnly'];
  309. }
  310. /**
  311. * Set whether or not this is an HTTP only cookie.
  312. *
  313. * @param bool $httpOnly Set to true or false if this is HTTP only
  314. */
  315. public function setHttpOnly($httpOnly): void
  316. {
  317. if (!is_bool($httpOnly)) {
  318. trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a bool to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__);
  319. }
  320. $this->data['HttpOnly'] = (bool) $httpOnly;
  321. }
  322. /**
  323. * Check if the cookie matches a path value.
  324. *
  325. * A request-path path-matches a given cookie-path if at least one of
  326. * the following conditions holds:
  327. *
  328. * - The cookie-path and the request-path are identical.
  329. * - The cookie-path is a prefix of the request-path, and the last
  330. * character of the cookie-path is %x2F ("/").
  331. * - The cookie-path is a prefix of the request-path, and the first
  332. * character of the request-path that is not included in the cookie-
  333. * path is a %x2F ("/") character.
  334. *
  335. * @param string $requestPath Path to check against
  336. */
  337. public function matchesPath(string $requestPath): bool
  338. {
  339. $cookiePath = $this->getPath();
  340. // Match on exact matches or when path is the default empty "/"
  341. if ($cookiePath === '/' || $cookiePath == $requestPath) {
  342. return true;
  343. }
  344. // Ensure that the cookie-path is a prefix of the request path.
  345. if (0 !== \strpos($requestPath, $cookiePath)) {
  346. return false;
  347. }
  348. // Match if the last character of the cookie-path is "/"
  349. if (\substr($cookiePath, -1, 1) === '/') {
  350. return true;
  351. }
  352. // Match if the first character not included in cookie path is "/"
  353. return \substr($requestPath, \strlen($cookiePath), 1) === '/';
  354. }
  355. /**
  356. * Check if the cookie matches a domain value.
  357. *
  358. * @param string $domain Domain to check against
  359. */
  360. public function matchesDomain(string $domain): bool
  361. {
  362. $cookieDomain = $this->getDomain();
  363. if (null === $cookieDomain) {
  364. return true;
  365. }
  366. // Remove the leading '.' as per spec in RFC 6265.
  367. // https://datatracker.ietf.org/doc/html/rfc6265#section-5.2.3
  368. $cookieDomain = \ltrim(\strtolower($cookieDomain), '.');
  369. $domain = \strtolower($domain);
  370. // Domain not set or exact match.
  371. if ('' === $cookieDomain || $domain === $cookieDomain) {
  372. return true;
  373. }
  374. // Matching the subdomain according to RFC 6265.
  375. // https://datatracker.ietf.org/doc/html/rfc6265#section-5.1.3
  376. if (\filter_var($domain, \FILTER_VALIDATE_IP)) {
  377. return false;
  378. }
  379. return (bool) \preg_match('/\.'.\preg_quote($cookieDomain, '/').'$/', $domain);
  380. }
  381. /**
  382. * Check if the cookie is expired.
  383. */
  384. public function isExpired(): bool
  385. {
  386. return $this->getExpires() !== null && \time() > $this->getExpires();
  387. }
  388. /**
  389. * Check if the cookie is valid according to RFC 6265.
  390. *
  391. * @return bool|string Returns true if valid or an error message if invalid
  392. */
  393. public function validate()
  394. {
  395. $name = $this->getName();
  396. if ($name === '') {
  397. return 'The cookie name must not be empty';
  398. }
  399. // Check if any of the invalid characters are present in the cookie name
  400. if (\preg_match(
  401. '/[\x00-\x20\x22\x28-\x29\x2c\x2f\x3a-\x40\x5c\x7b\x7d\x7f]/',
  402. $name
  403. )) {
  404. return 'Cookie name must not contain invalid characters: ASCII '
  405. .'Control characters (0-31;127), space, tab and the '
  406. .'following characters: ()<>@,;:\"/?={}';
  407. }
  408. // Value must not be null. 0 and empty string are valid. Empty strings
  409. // are technically against RFC 6265, but known to happen in the wild.
  410. $value = $this->getValue();
  411. if ($value === null) {
  412. return 'The cookie value must not be empty';
  413. }
  414. // Domains must not be empty, but can be 0. "0" is not a valid internet
  415. // domain, but may be used as server name in a private network.
  416. $domain = $this->getDomain();
  417. if ($domain === null || $domain === '') {
  418. return 'The cookie domain must not be empty';
  419. }
  420. return true;
  421. }
  422. }