2 namespace GuzzleHttp\Cookie;
10 private static $defaults = [
22 /** @var array Cookie data */
26 * Create a new SetCookie object from a string
28 * @param string $cookie Set-Cookie header string
32 public static function fromString($cookie)
34 // Create the default return array
35 $data = self::$defaults;
36 // Explode the cookie string using a series of semicolons
37 $pieces = array_filter(array_map('trim', explode(';', $cookie)));
38 // The name of the cookie (first kvp) must exist and include an equal sign.
39 if (empty($pieces[0]) || !strpos($pieces[0], '=')) {
40 return new self($data);
43 // Add the cookie pieces into the parsed data array
44 foreach ($pieces as $part) {
45 $cookieParts = explode('=', $part, 2);
46 $key = trim($cookieParts[0]);
47 $value = isset($cookieParts[1])
48 ? trim($cookieParts[1], " \n\r\t\0\x0B")
51 // Only check for non-cookies when cookies have been found
52 if (empty($data['Name'])) {
54 $data['Value'] = $value;
56 foreach (array_keys(self::$defaults) as $search) {
57 if (!strcasecmp($search, $key)) {
58 $data[$search] = $value;
66 return new self($data);
70 * @param array $data Array of cookie data provided by a Cookie parser
72 public function __construct(array $data = [])
74 $this->data = array_replace(self::$defaults, $data);
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 ($this->getExpires() && !is_numeric($this->getExpires())) {
80 $this->setExpires($this->getExpires());
84 public function __toString()
86 $str = $this->data['Name'] . '=' . $this->data['Value'] . '; ';
87 foreach ($this->data as $k => $v) {
88 if ($k !== 'Name' && $k !== 'Value' && $v !== null && $v !== false) {
89 if ($k === 'Expires') {
90 $str .= 'Expires=' . gmdate('D, d M Y H:i:s \G\M\T', $v) . '; ';
92 $str .= ($v === true ? $k : "{$k}={$v}") . '; ';
97 return rtrim($str, '; ');
100 public function toArray()
106 * Get the cookie name
110 public function getName()
112 return $this->data['Name'];
116 * Set the cookie name
118 * @param string $name Cookie name
120 public function setName($name)
122 $this->data['Name'] = $name;
126 * Get the cookie value
130 public function getValue()
132 return $this->data['Value'];
136 * Set the cookie value
138 * @param string $value Cookie value
140 public function setValue($value)
142 $this->data['Value'] = $value;
148 * @return string|null
150 public function getDomain()
152 return $this->data['Domain'];
156 * Set the domain of the cookie
158 * @param string $domain
160 public function setDomain($domain)
162 $this->data['Domain'] = $domain;
170 public function getPath()
172 return $this->data['Path'];
176 * Set the path of the cookie
178 * @param string $path Path of the cookie
180 public function setPath($path)
182 $this->data['Path'] = $path;
186 * Maximum lifetime of the cookie in seconds
190 public function getMaxAge()
192 return $this->data['Max-Age'];
196 * Set the max-age of the cookie
198 * @param int $maxAge Max age of the cookie in seconds
200 public function setMaxAge($maxAge)
202 $this->data['Max-Age'] = $maxAge;
206 * The UNIX timestamp when the cookie Expires
210 public function getExpires()
212 return $this->data['Expires'];
216 * Set the unix timestamp for which the cookie will expire
218 * @param int $timestamp Unix timestamp
220 public function setExpires($timestamp)
222 $this->data['Expires'] = is_numeric($timestamp)
224 : strtotime($timestamp);
228 * Get whether or not this is a secure cookie
232 public function getSecure()
234 return $this->data['Secure'];
238 * Set whether or not the cookie is secure
240 * @param bool $secure Set to true or false if secure
242 public function setSecure($secure)
244 $this->data['Secure'] = $secure;
248 * Get whether or not this is a session cookie
252 public function getDiscard()
254 return $this->data['Discard'];
258 * Set whether or not this is a session cookie
260 * @param bool $discard Set to true or false if this is a session cookie
262 public function setDiscard($discard)
264 $this->data['Discard'] = $discard;
268 * Get whether or not this is an HTTP only cookie
272 public function getHttpOnly()
274 return $this->data['HttpOnly'];
278 * Set whether or not this is an HTTP only cookie
280 * @param bool $httpOnly Set to true or false if this is HTTP only
282 public function setHttpOnly($httpOnly)
284 $this->data['HttpOnly'] = $httpOnly;
288 * Check if the cookie matches a path value.
290 * A request-path path-matches a given cookie-path if at least one of
291 * the following conditions holds:
293 * - The cookie-path and the request-path are identical.
294 * - The cookie-path is a prefix of the request-path, and the last
295 * character of the cookie-path is %x2F ("/").
296 * - The cookie-path is a prefix of the request-path, and the first
297 * character of the request-path that is not included in the cookie-
298 * path is a %x2F ("/") character.
300 * @param string $requestPath Path to check against
304 public function matchesPath($requestPath)
306 $cookiePath = $this->getPath();
308 // Match on exact matches or when path is the default empty "/"
309 if ($cookiePath === '/' || $cookiePath == $requestPath) {
313 // Ensure that the cookie-path is a prefix of the request path.
314 if (0 !== strpos($requestPath, $cookiePath)) {
318 // Match if the last character of the cookie-path is "/"
319 if (substr($cookiePath, -1, 1) === '/') {
323 // Match if the first character not included in cookie path is "/"
324 return substr($requestPath, strlen($cookiePath), 1) === '/';
328 * Check if the cookie matches a domain value
330 * @param string $domain Domain to check against
334 public function matchesDomain($domain)
336 // Remove the leading '.' as per spec in RFC 6265.
337 // http://tools.ietf.org/html/rfc6265#section-5.2.3
338 $cookieDomain = ltrim($this->getDomain(), '.');
340 // Domain not set or exact match.
341 if (!$cookieDomain || !strcasecmp($domain, $cookieDomain)) {
345 // Matching the subdomain according to RFC 6265.
346 // http://tools.ietf.org/html/rfc6265#section-5.1.3
347 if (filter_var($domain, FILTER_VALIDATE_IP)) {
351 return (bool) preg_match('/\.' . preg_quote($cookieDomain, '/') . '$/', $domain);
355 * Check if the cookie is expired
359 public function isExpired()
361 return $this->getExpires() !== null && time() > $this->getExpires();
365 * Check if the cookie is valid according to RFC 6265
367 * @return bool|string Returns true if valid or an error message if invalid
369 public function validate()
371 // Names must not be empty, but can be 0
372 $name = $this->getName();
373 if (empty($name) && !is_numeric($name)) {
374 return 'The cookie name must not be empty';
377 // Check if any of the invalid characters are present in the cookie name
379 '/[\x00-\x20\x22\x28-\x29\x2c\x2f\x3a-\x40\x5c\x7b\x7d\x7f]/',
382 return 'Cookie name must not contain invalid characters: ASCII '
383 . 'Control characters (0-31;127), space, tab and the '
384 . 'following characters: ()<>@,;:\"/?={}';
387 // Value must not be empty, but can be 0
388 $value = $this->getValue();
389 if (empty($value) && !is_numeric($value)) {
390 return 'The cookie value must not be empty';
393 // Domains must not be empty, but can be 0
394 // A "0" is not a valid internet domain, but may be used as server name
395 // in a private network.
396 $domain = $this->getDomain();
397 if (empty($domain) && !is_numeric($domain)) {
398 return 'The cookie domain must not be empty';