SetCookie.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  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. $data[$search] = $value;
  56. continue 2;
  57. }
  58. }
  59. $data[$key] = $value;
  60. }
  61. }
  62. return new self($data);
  63. }
  64. /**
  65. * @param array $data Array of cookie data provided by a Cookie parser
  66. */
  67. public function __construct(array $data = [])
  68. {
  69. /** @var array|null $replaced will be null in case of replace error */
  70. $replaced = \array_replace(self::$defaults, $data);
  71. if ($replaced === null) {
  72. throw new \InvalidArgumentException('Unable to replace the default values for the Cookie.');
  73. }
  74. $this->data = $replaced;
  75. // Extract the Expires value and turn it into a UNIX timestamp if needed
  76. if (!$this->getExpires() && $this->getMaxAge()) {
  77. // Calculate the Expires date
  78. $this->setExpires(\time() + $this->getMaxAge());
  79. } elseif (null !== ($expires = $this->getExpires()) && !\is_numeric($expires)) {
  80. $this->setExpires($expires);
  81. }
  82. }
  83. public function __toString()
  84. {
  85. $str = $this->data['Name'] . '=' . $this->data['Value'] . '; ';
  86. foreach ($this->data as $k => $v) {
  87. if ($k !== 'Name' && $k !== 'Value' && $v !== null && $v !== false) {
  88. if ($k === 'Expires') {
  89. $str .= 'Expires=' . \gmdate('D, d M Y H:i:s \G\M\T', $v) . '; ';
  90. } else {
  91. $str .= ($v === true ? $k : "{$k}={$v}") . '; ';
  92. }
  93. }
  94. }
  95. return \rtrim($str, '; ');
  96. }
  97. public function toArray(): array
  98. {
  99. return $this->data;
  100. }
  101. /**
  102. * Get the cookie name.
  103. *
  104. * @return string
  105. */
  106. public function getName()
  107. {
  108. return $this->data['Name'];
  109. }
  110. /**
  111. * Set the cookie name.
  112. *
  113. * @param string $name Cookie name
  114. */
  115. public function setName($name): void
  116. {
  117. $this->data['Name'] = $name;
  118. }
  119. /**
  120. * Get the cookie value.
  121. *
  122. * @return string|null
  123. */
  124. public function getValue()
  125. {
  126. return $this->data['Value'];
  127. }
  128. /**
  129. * Set the cookie value.
  130. *
  131. * @param string $value Cookie value
  132. */
  133. public function setValue($value): void
  134. {
  135. $this->data['Value'] = $value;
  136. }
  137. /**
  138. * Get the domain.
  139. *
  140. * @return string|null
  141. */
  142. public function getDomain()
  143. {
  144. return $this->data['Domain'];
  145. }
  146. /**
  147. * Set the domain of the cookie.
  148. *
  149. * @param string $domain
  150. */
  151. public function setDomain($domain): void
  152. {
  153. $this->data['Domain'] = $domain;
  154. }
  155. /**
  156. * Get the path.
  157. *
  158. * @return string
  159. */
  160. public function getPath()
  161. {
  162. return $this->data['Path'];
  163. }
  164. /**
  165. * Set the path of the cookie.
  166. *
  167. * @param string $path Path of the cookie
  168. */
  169. public function setPath($path): void
  170. {
  171. $this->data['Path'] = $path;
  172. }
  173. /**
  174. * Maximum lifetime of the cookie in seconds.
  175. *
  176. * @return int|null
  177. */
  178. public function getMaxAge()
  179. {
  180. return $this->data['Max-Age'];
  181. }
  182. /**
  183. * Set the max-age of the cookie.
  184. *
  185. * @param int $maxAge Max age of the cookie in seconds
  186. */
  187. public function setMaxAge($maxAge): void
  188. {
  189. $this->data['Max-Age'] = $maxAge;
  190. }
  191. /**
  192. * The UNIX timestamp when the cookie Expires.
  193. *
  194. * @return string|int|null
  195. */
  196. public function getExpires()
  197. {
  198. return $this->data['Expires'];
  199. }
  200. /**
  201. * Set the unix timestamp for which the cookie will expire.
  202. *
  203. * @param int|string $timestamp Unix timestamp or any English textual datetime description.
  204. */
  205. public function setExpires($timestamp): void
  206. {
  207. $this->data['Expires'] = \is_numeric($timestamp)
  208. ? (int) $timestamp
  209. : \strtotime($timestamp);
  210. }
  211. /**
  212. * Get whether or not this is a secure cookie.
  213. *
  214. * @return bool|null
  215. */
  216. public function getSecure()
  217. {
  218. return $this->data['Secure'];
  219. }
  220. /**
  221. * Set whether or not the cookie is secure.
  222. *
  223. * @param bool $secure Set to true or false if secure
  224. */
  225. public function setSecure($secure): void
  226. {
  227. $this->data['Secure'] = $secure;
  228. }
  229. /**
  230. * Get whether or not this is a session cookie.
  231. *
  232. * @return bool|null
  233. */
  234. public function getDiscard()
  235. {
  236. return $this->data['Discard'];
  237. }
  238. /**
  239. * Set whether or not this is a session cookie.
  240. *
  241. * @param bool $discard Set to true or false if this is a session cookie
  242. */
  243. public function setDiscard($discard): void
  244. {
  245. $this->data['Discard'] = $discard;
  246. }
  247. /**
  248. * Get whether or not this is an HTTP only cookie.
  249. *
  250. * @return bool
  251. */
  252. public function getHttpOnly()
  253. {
  254. return $this->data['HttpOnly'];
  255. }
  256. /**
  257. * Set whether or not this is an HTTP only cookie.
  258. *
  259. * @param bool $httpOnly Set to true or false if this is HTTP only
  260. */
  261. public function setHttpOnly($httpOnly): void
  262. {
  263. $this->data['HttpOnly'] = $httpOnly;
  264. }
  265. /**
  266. * Check if the cookie matches a path value.
  267. *
  268. * A request-path path-matches a given cookie-path if at least one of
  269. * the following conditions holds:
  270. *
  271. * - The cookie-path and the request-path are identical.
  272. * - The cookie-path is a prefix of the request-path, and the last
  273. * character of the cookie-path is %x2F ("/").
  274. * - The cookie-path is a prefix of the request-path, and the first
  275. * character of the request-path that is not included in the cookie-
  276. * path is a %x2F ("/") character.
  277. *
  278. * @param string $requestPath Path to check against
  279. */
  280. public function matchesPath(string $requestPath): bool
  281. {
  282. $cookiePath = $this->getPath();
  283. // Match on exact matches or when path is the default empty "/"
  284. if ($cookiePath === '/' || $cookiePath == $requestPath) {
  285. return true;
  286. }
  287. // Ensure that the cookie-path is a prefix of the request path.
  288. if (0 !== \strpos($requestPath, $cookiePath)) {
  289. return false;
  290. }
  291. // Match if the last character of the cookie-path is "/"
  292. if (\substr($cookiePath, -1, 1) === '/') {
  293. return true;
  294. }
  295. // Match if the first character not included in cookie path is "/"
  296. return \substr($requestPath, \strlen($cookiePath), 1) === '/';
  297. }
  298. /**
  299. * Check if the cookie matches a domain value.
  300. *
  301. * @param string $domain Domain to check against
  302. */
  303. public function matchesDomain(string $domain): bool
  304. {
  305. $cookieDomain = $this->getDomain();
  306. if (null === $cookieDomain) {
  307. return true;
  308. }
  309. // Remove the leading '.' as per spec in RFC 6265.
  310. // https://tools.ietf.org/html/rfc6265#section-5.2.3
  311. $cookieDomain = \ltrim($cookieDomain, '.');
  312. // Domain not set or exact match.
  313. if (!$cookieDomain || !\strcasecmp($domain, $cookieDomain)) {
  314. return true;
  315. }
  316. // Matching the subdomain according to RFC 6265.
  317. // https://tools.ietf.org/html/rfc6265#section-5.1.3
  318. if (\filter_var($domain, \FILTER_VALIDATE_IP)) {
  319. return false;
  320. }
  321. return (bool) \preg_match('/\.' . \preg_quote($cookieDomain, '/') . '$/', $domain);
  322. }
  323. /**
  324. * Check if the cookie is expired.
  325. */
  326. public function isExpired(): bool
  327. {
  328. return $this->getExpires() !== null && \time() > $this->getExpires();
  329. }
  330. /**
  331. * Check if the cookie is valid according to RFC 6265.
  332. *
  333. * @return bool|string Returns true if valid or an error message if invalid
  334. */
  335. public function validate()
  336. {
  337. $name = $this->getName();
  338. if ($name === '') {
  339. return 'The cookie name must not be empty';
  340. }
  341. // Check if any of the invalid characters are present in the cookie name
  342. if (\preg_match(
  343. '/[\x00-\x20\x22\x28-\x29\x2c\x2f\x3a-\x40\x5c\x7b\x7d\x7f]/',
  344. $name
  345. )) {
  346. return 'Cookie name must not contain invalid characters: ASCII '
  347. . 'Control characters (0-31;127), space, tab and the '
  348. . 'following characters: ()<>@,;:\"/?={}';
  349. }
  350. // Value must not be null. 0 and empty string are valid. Empty strings
  351. // are technically against RFC 6265, but known to happen in the wild.
  352. $value = $this->getValue();
  353. if ($value === null) {
  354. return 'The cookie value must not be empty';
  355. }
  356. // Domains must not be empty, but can be 0. "0" is not a valid internet
  357. // domain, but may be used as server name in a private network.
  358. $domain = $this->getDomain();
  359. if ($domain === null || $domain === '') {
  360. return 'The cookie domain must not be empty';
  361. }
  362. return true;
  363. }
  364. }