Cookie.php 8.2 KB

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