Cookie.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. <?php
  2. namespace Qii\Http;
  3. use Qii\Exceptions\InvalidParams;
  4. /**
  5. * Represents a cookie.
  6. * 使用方法:
  7. * controller中使用
  8. * $this->response->setHeader("Set-Cookie", new Cookie($name, $value = null, $expire = 0, $path = '/', $domain = null, $secure = null, $httpOnly = true, $raw = false, $sameSite = 'lax'))->response()
  9. */
  10. class Cookie
  11. {
  12. const SAMESITE_NONE = 'none';
  13. const SAMESITE_LAX = 'lax';
  14. const SAMESITE_STRICT = 'strict';
  15. protected $name;
  16. protected $value;
  17. protected $domain;
  18. protected $expire;
  19. protected $path;
  20. protected $secure;
  21. protected $httpOnly;
  22. private $raw;
  23. private $sameSite;
  24. private $secureDefault = false;
  25. const RESERVED_CHARS_LIST = "=,; \t\r\n\v\f";
  26. const RESERVED_CHARS_FROM = ['=', ',', ';', ' ', "\t", "\r", "\n", "\v", "\f"];
  27. const RESERVED_CHARS_TO = ['%3D', '%2C', '%3B', '%20', '%09', '%0D', '%0A', '%0B', '%0C'];
  28. /**
  29. * Creates cookie from raw header string.
  30. *
  31. * @return static
  32. */
  33. public static function fromString($cookie, $decode = false)
  34. {
  35. $data = [
  36. 'expires' => 0,
  37. 'path' => '/',
  38. 'domain' => null,
  39. 'secure' => false,
  40. 'httponly' => false,
  41. 'raw' => !$decode,
  42. 'samesite' => null,
  43. ];
  44. $parts = HeaderUtils::split($cookie, ';=');
  45. $part = array_shift($parts);
  46. $name = $decode ? urldecode($part[0]) : $part[0];
  47. $value = isset($part[1]) ? ($decode ? urldecode($part[1]) : $part[1]) : null;
  48. $data = HeaderUtils::combine($parts) + $data;
  49. $data['expires'] = self::expiresTimestamp($data['expires']);
  50. if (isset($data['max-age']) && ($data['max-age'] > 0 || $data['expires'] > time())) {
  51. $data['expires'] = time() + (int) $data['max-age'];
  52. }
  53. return new static($name, $value, $data['expires'], $data['path'], $data['domain'], $data['secure'], $data['httponly'], $data['raw'], $data['samesite']);
  54. }
  55. public static function create(string $name, string $value = null, $expire = 0, $path = '/', $domain = null, $secure = null, $httpOnly = true, $raw = false, $sameSite = self::SAMESITE_LAX): self
  56. {
  57. return new self($name, $value, $expire, $path, $domain, $secure, $httpOnly, $raw, $sameSite);
  58. }
  59. /**
  60. * @param string $name The name of the cookie
  61. * @param string|null $value The value of the cookie
  62. * @param int|string|\DateTimeInterface $expire The time the cookie expires
  63. * @param string $path The path on the server in which the cookie will be available on
  64. * @param string|null $domain The domain that the cookie is available to
  65. * @param bool|null $secure Whether the client should send back the cookie only over HTTPS or null to auto-enable this when the request is already using HTTPS
  66. * @param bool $httpOnly Whether the cookie will be made accessible only through the HTTP protocol
  67. * @param bool $raw Whether the cookie value should be sent with no url encoding
  68. * @param string|null $sameSite Whether the cookie will be available for cross-site requests
  69. *
  70. * @throws InvalidParams
  71. */
  72. public function __construct($name, $value = null, $expire = 0, $path = '/', $domain = null, $secure = null, $httpOnly = true, $raw = false, $sameSite = 'lax')
  73. {
  74. // from PHP source code
  75. if ($raw && false !== strpbrk($name, self::RESERVED_CHARS_LIST)) {
  76. throw new InvalidParams(sprintf('The cookie name "%s" contains invalid characters.', $name));
  77. }
  78. if (empty($name)) {
  79. throw new InvalidParams('The cookie name cannot be empty.');
  80. }
  81. $this->name = $name;
  82. $this->value = $value;
  83. $this->domain = $domain;
  84. $this->expire = self::expiresTimestamp($expire);
  85. $this->path = empty($path) ? '/' : $path;
  86. $this->secure = $secure;
  87. $this->httpOnly = $httpOnly;
  88. $this->raw = $raw;
  89. $this->sameSite = $this->withSameSite($sameSite)->sameSite;
  90. }
  91. /**
  92. * Creates a cookie copy with a new value.
  93. *
  94. * @return static
  95. */
  96. public function withValue($value): self
  97. {
  98. $cookie = clone $this;
  99. $cookie->value = $value;
  100. return $cookie;
  101. }
  102. /**
  103. * Creates a cookie copy with a new domain that the cookie is available to.
  104. *
  105. * @return static
  106. */
  107. public function withDomain($domain): self
  108. {
  109. $cookie = clone $this;
  110. $cookie->domain = $domain;
  111. return $cookie;
  112. }
  113. /**
  114. * Creates a cookie copy with a new time the cookie expires.
  115. *
  116. * @param int|string|\DateTimeInterface $expire
  117. *
  118. * @return static
  119. */
  120. public function withExpires($expire = 0): self
  121. {
  122. $cookie = clone $this;
  123. $cookie->expire = self::expiresTimestamp($expire);
  124. return $cookie;
  125. }
  126. /**
  127. * Converts expires formats to a unix timestamp.
  128. *
  129. * @param int|string|\DateTimeInterface $expire
  130. */
  131. private static function expiresTimestamp($expire = 0): int
  132. {
  133. // convert expiration time to a Unix timestamp
  134. if ($expire instanceof \DateTimeInterface) {
  135. $expire = $expire->format('U');
  136. } elseif (!is_numeric($expire)) {
  137. $expire = strtotime($expire);
  138. if (false === $expire) {
  139. throw new InvalidParams('The cookie expiration time is not valid.');
  140. }
  141. }
  142. return 0 < $expire ? (int) $expire : 0;
  143. }
  144. /**
  145. * Creates a cookie copy with a new path on the server in which the cookie will be available on.
  146. *
  147. * @return static
  148. */
  149. public function withPath(string $path): self
  150. {
  151. $cookie = clone $this;
  152. $cookie->path = '' === $path ? '/' : $path;
  153. return $cookie;
  154. }
  155. /**
  156. * Creates a cookie copy that only be transmitted over a secure HTTPS connection from the client.
  157. *
  158. * @return static
  159. */
  160. public function withSecure(bool $secure = true): self
  161. {
  162. $cookie = clone $this;
  163. $cookie->secure = $secure;
  164. return $cookie;
  165. }
  166. /**
  167. * Creates a cookie copy that be accessible only through the HTTP protocol.
  168. *
  169. * @return static
  170. */
  171. public function withHttpOnly(bool $httpOnly = true): self
  172. {
  173. $cookie = clone $this;
  174. $cookie->httpOnly = $httpOnly;
  175. return $cookie;
  176. }
  177. /**
  178. * Creates a cookie copy that uses no url encoding.
  179. *
  180. * @return static
  181. */
  182. public function withRaw(bool $raw = true): self
  183. {
  184. if ($raw && false !== strpbrk($this->name, self::RESERVED_CHARS_LIST)) {
  185. throw new InvalidParams(sprintf('The cookie name "%s" contains invalid characters.', $this->name));
  186. }
  187. $cookie = clone $this;
  188. $cookie->raw = $raw;
  189. return $cookie;
  190. }
  191. /**
  192. * Creates a cookie copy with SameSite attribute.
  193. *
  194. * @return static
  195. */
  196. public function withSameSite($sameSite): self
  197. {
  198. if ('' === $sameSite) {
  199. $sameSite = null;
  200. } elseif (null !== $sameSite) {
  201. $sameSite = strtolower($sameSite);
  202. }
  203. if (!\in_array($sameSite, [self::SAMESITE_LAX, self::SAMESITE_STRICT, self::SAMESITE_NONE, null], true)) {
  204. throw new InvalidParams('The "sameSite" parameter value is not valid.');
  205. }
  206. $cookie = clone $this;
  207. $cookie->sameSite = $sameSite;
  208. return $cookie;
  209. }
  210. /**
  211. * Returns the cookie as a string.
  212. *
  213. * @return string
  214. */
  215. public function __toString()
  216. {
  217. if ($this->isRaw()) {
  218. $str = $this->getName();
  219. } else {
  220. $str = str_replace(self::RESERVED_CHARS_FROM, self::RESERVED_CHARS_TO, $this->getName());
  221. }
  222. $str .= '=';
  223. if ('' === (string) $this->getValue()) {
  224. $str .= 'deleted; expires='.gmdate('D, d-M-Y H:i:s T', time() - 31536001).'; Max-Age=0';
  225. } else {
  226. $str .= $this->isRaw() ? $this->getValue() : rawurlencode($this->getValue());
  227. if (0 !== $this->getExpiresTime()) {
  228. $str .= '; expires='.gmdate('D, d-M-Y H:i:s T', $this->getExpiresTime()).'; Max-Age='.$this->getMaxAge();
  229. }
  230. }
  231. if ($this->getPath()) {
  232. $str .= '; path='.$this->getPath();
  233. }
  234. if ($this->getDomain()) {
  235. $str .= '; domain='.$this->getDomain();
  236. }
  237. if (true === $this->isSecure()) {
  238. $str .= '; secure';
  239. }
  240. if (true === $this->isHttpOnly()) {
  241. $str .= '; httponly';
  242. }
  243. if (null !== $this->getSameSite()) {
  244. $str .= '; samesite='.$this->getSameSite();
  245. }
  246. return $str;
  247. }
  248. /**
  249. * Gets the name of the cookie.
  250. *
  251. * @return string
  252. */
  253. public function getName()
  254. {
  255. return $this->name;
  256. }
  257. /**
  258. * Gets the value of the cookie.
  259. *
  260. * @return string|null
  261. */
  262. public function getValue()
  263. {
  264. return $this->value;
  265. }
  266. /**
  267. * Gets the domain that the cookie is available to.
  268. *
  269. * @return string|null
  270. */
  271. public function getDomain()
  272. {
  273. return $this->domain;
  274. }
  275. /**
  276. * Gets the time the cookie expires.
  277. *
  278. * @return int
  279. */
  280. public function getExpiresTime()
  281. {
  282. return $this->expire;
  283. }
  284. /**
  285. * Gets the max-age attribute.
  286. *
  287. * @return int
  288. */
  289. public function getMaxAge()
  290. {
  291. $maxAge = $this->expire - time();
  292. return 0 >= $maxAge ? 0 : $maxAge;
  293. }
  294. /**
  295. * Gets the path on the server in which the cookie will be available on.
  296. *
  297. * @return string
  298. */
  299. public function getPath()
  300. {
  301. return $this->path;
  302. }
  303. /**
  304. * Checks whether the cookie should only be transmitted over a secure HTTPS connection from the client.
  305. *
  306. * @return bool
  307. */
  308. public function isSecure()
  309. {
  310. return $this->secure ?? $this->secureDefault;
  311. }
  312. /**
  313. * Checks whether the cookie will be made accessible only through the HTTP protocol.
  314. *
  315. * @return bool
  316. */
  317. public function isHttpOnly()
  318. {
  319. return $this->httpOnly;
  320. }
  321. /**
  322. * Whether this cookie is about to be cleared.
  323. *
  324. * @return bool
  325. */
  326. public function isCleared()
  327. {
  328. return 0 !== $this->expire && $this->expire < time();
  329. }
  330. /**
  331. * Checks if the cookie value should be sent with no url encoding.
  332. *
  333. * @return bool
  334. */
  335. public function isRaw()
  336. {
  337. return $this->raw;
  338. }
  339. /**
  340. * Gets the SameSite attribute.
  341. *
  342. * @return string|null
  343. */
  344. public function getSameSite()
  345. {
  346. return $this->sameSite;
  347. }
  348. /**
  349. * @param bool $default The default value of the "secure" flag when it is set to null
  350. */
  351. public function setSecureDefault(bool $default)
  352. {
  353. $this->secureDefault = $default;
  354. }
  355. }