Cookie.php 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  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 = [
  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($name, $value, $expires = null, $path = null, $domain = '', $secure = false, $httponly = true, $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 = (bool) $secure;
  64. $this->httponly = (bool) $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 = [
  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. /**
  164. * @param string $dateValue
  165. *
  166. * @return string|null
  167. */
  168. private static function parseDate($dateValue)
  169. {
  170. // trim single quotes around date if present
  171. if (($length = \strlen($dateValue)) > 1 && "'" === $dateValue[0] && "'" === $dateValue[$length - 1]) {
  172. $dateValue = substr($dateValue, 1, -1);
  173. }
  174. foreach (self::$dateFormats as $dateFormat) {
  175. if (false !== $date = \DateTime::createFromFormat($dateFormat, $dateValue, new \DateTimeZone('GMT'))) {
  176. return $date->format('U');
  177. }
  178. }
  179. // attempt a fallback for unusual formatting
  180. if (false !== $date = date_create($dateValue, new \DateTimeZone('GMT'))) {
  181. return $date->format('U');
  182. }
  183. return null;
  184. }
  185. /**
  186. * Gets the name of the cookie.
  187. *
  188. * @return string The cookie name
  189. */
  190. public function getName()
  191. {
  192. return $this->name;
  193. }
  194. /**
  195. * Gets the value of the cookie.
  196. *
  197. * @return string The cookie value
  198. */
  199. public function getValue()
  200. {
  201. return $this->value;
  202. }
  203. /**
  204. * Gets the raw value of the cookie.
  205. *
  206. * @return string The cookie value
  207. */
  208. public function getRawValue()
  209. {
  210. return $this->rawValue;
  211. }
  212. /**
  213. * Gets the expires time of the cookie.
  214. *
  215. * @return string|null The cookie expires time
  216. */
  217. public function getExpiresTime()
  218. {
  219. return $this->expires;
  220. }
  221. /**
  222. * Gets the path of the cookie.
  223. *
  224. * @return string The cookie path
  225. */
  226. public function getPath()
  227. {
  228. return $this->path;
  229. }
  230. /**
  231. * Gets the domain of the cookie.
  232. *
  233. * @return string The cookie domain
  234. */
  235. public function getDomain()
  236. {
  237. return $this->domain;
  238. }
  239. /**
  240. * Returns the secure flag of the cookie.
  241. *
  242. * @return bool The cookie secure flag
  243. */
  244. public function isSecure()
  245. {
  246. return $this->secure;
  247. }
  248. /**
  249. * Returns the httponly flag of the cookie.
  250. *
  251. * @return bool The cookie httponly flag
  252. */
  253. public function isHttpOnly()
  254. {
  255. return $this->httponly;
  256. }
  257. /**
  258. * Returns true if the cookie has expired.
  259. *
  260. * @return bool true if the cookie has expired, false otherwise
  261. */
  262. public function isExpired()
  263. {
  264. return null !== $this->expires && 0 != $this->expires && $this->expires < time();
  265. }
  266. }