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 include an equal sign.
39 if (empty($pieces) || !strpos($pieces[0], '=')) {
40 return new self($data);
43 // Add the cookie pieces into the parsed data array
44 foreach ($pieces as $part) {
46 $cookieParts = explode('=', $part, 2);
47 $key = trim($cookieParts[0]);
48 $value = isset($cookieParts[1])
49 ? trim($cookieParts[1], " \n\r\t\0\x0B")
52 // Only check for non-cookies when cookies have been found
53 if (empty($data['Name'])) {
55 $data['Value'] = $value;
57 foreach (array_keys(self::$defaults) as $search) {
58 if (!strcasecmp($search, $key)) {
59 $data[$search] = $value;
67 return new self($data);
71 * @param array $data Array of cookie data provided by a Cookie parser
73 public function __construct(array $data = [])
75 $this->data = array_replace(self::$defaults, $data);
76 // Extract the Expires value and turn it into a UNIX timestamp if needed
77 if (!$this->getExpires() && $this->getMaxAge()) {
78 // Calculate the Expires date
79 $this->setExpires(time() + $this->getMaxAge());
80 } elseif ($this->getExpires() && !is_numeric($this->getExpires())) {
81 $this->setExpires($this->getExpires());
85 public function __toString()
87 $str = $this->data['Name'] . '=' . $this->data['Value'] . '; ';
88 foreach ($this->data as $k => $v) {
89 if ($k !== 'Name' && $k !== 'Value' && $v !== null && $v !== false) {
90 if ($k === 'Expires') {
91 $str .= 'Expires=' . gmdate('D, d M Y H:i:s \G\M\T', $v) . '; ';
93 $str .= ($v === true ? $k : "{$k}={$v}") . '; ';
98 return rtrim($str, '; ');
101 public function toArray()
107 * Get the cookie name
111 public function getName()
113 return $this->data['Name'];
117 * Set the cookie name
119 * @param string $name Cookie name
121 public function setName($name)
123 $this->data['Name'] = $name;
127 * Get the cookie value
131 public function getValue()
133 return $this->data['Value'];
137 * Set the cookie value
139 * @param string $value Cookie value
141 public function setValue($value)
143 $this->data['Value'] = $value;
149 * @return string|null
151 public function getDomain()
153 return $this->data['Domain'];
157 * Set the domain of the cookie
159 * @param string $domain
161 public function setDomain($domain)
163 $this->data['Domain'] = $domain;
171 public function getPath()
173 return $this->data['Path'];
177 * Set the path of the cookie
179 * @param string $path Path of the cookie
181 public function setPath($path)
183 $this->data['Path'] = $path;
187 * Maximum lifetime of the cookie in seconds
191 public function getMaxAge()
193 return $this->data['Max-Age'];
197 * Set the max-age of the cookie
199 * @param int $maxAge Max age of the cookie in seconds
201 public function setMaxAge($maxAge)
203 $this->data['Max-Age'] = $maxAge;
207 * The UNIX timestamp when the cookie Expires
211 public function getExpires()
213 return $this->data['Expires'];
217 * Set the unix timestamp for which the cookie will expire
219 * @param int $timestamp Unix timestamp
221 public function setExpires($timestamp)
223 $this->data['Expires'] = is_numeric($timestamp)
225 : strtotime($timestamp);
229 * Get whether or not this is a secure cookie
233 public function getSecure()
235 return $this->data['Secure'];
239 * Set whether or not the cookie is secure
241 * @param bool $secure Set to true or false if secure
243 public function setSecure($secure)
245 $this->data['Secure'] = $secure;
249 * Get whether or not this is a session cookie
253 public function getDiscard()
255 return $this->data['Discard'];
259 * Set whether or not this is a session cookie
261 * @param bool $discard Set to true or false if this is a session cookie
263 public function setDiscard($discard)
265 $this->data['Discard'] = $discard;
269 * Get whether or not this is an HTTP only cookie
273 public function getHttpOnly()
275 return $this->data['HttpOnly'];
279 * Set whether or not this is an HTTP only cookie
281 * @param bool $httpOnly Set to true or false if this is HTTP only
283 public function setHttpOnly($httpOnly)
285 $this->data['HttpOnly'] = $httpOnly;
289 * Check if the cookie matches a path value.
291 * A request-path path-matches a given cookie-path if at least one of
292 * the following conditions holds:
294 * - The cookie-path and the request-path are identical.
295 * - The cookie-path is a prefix of the request-path, and the last
296 * character of the cookie-path is %x2F ("/").
297 * - The cookie-path is a prefix of the request-path, and the first
298 * character of the request-path that is not included in the cookie-
299 * path is a %x2F ("/") character.
301 * @param string $requestPath Path to check against
305 public function matchesPath($requestPath)
307 $cookiePath = $this->getPath();
309 // Match on exact matches or when path is the default empty "/"
310 if ($cookiePath === '/' || $cookiePath == $requestPath) {
314 // Ensure that the cookie-path is a prefix of the request path.
315 if (0 !== strpos($requestPath, $cookiePath)) {
319 // Match if the last character of the cookie-path is "/"
320 if (substr($cookiePath, -1, 1) === '/') {
324 // Match if the first character not included in cookie path is "/"
325 return substr($requestPath, strlen($cookiePath), 1) === '/';
329 * Check if the cookie matches a domain value
331 * @param string $domain Domain to check against
335 public function matchesDomain($domain)
337 // Remove the leading '.' as per spec in RFC 6265.
338 // http://tools.ietf.org/html/rfc6265#section-5.2.3
339 $cookieDomain = ltrim($this->getDomain(), '.');
341 // Domain not set or exact match.
342 if (!$cookieDomain || !strcasecmp($domain, $cookieDomain)) {
346 // Matching the subdomain according to RFC 6265.
347 // http://tools.ietf.org/html/rfc6265#section-5.1.3
348 if (filter_var($domain, FILTER_VALIDATE_IP)) {
352 return (bool) preg_match('/\.' . preg_quote($cookieDomain) . '$/', $domain);
356 * Check if the cookie is expired
360 public function isExpired()
362 return $this->getExpires() && time() > $this->getExpires();
366 * Check if the cookie is valid according to RFC 6265
368 * @return bool|string Returns true if valid or an error message if invalid
370 public function validate()
372 // Names must not be empty, but can be 0
373 $name = $this->getName();
374 if (empty($name) && !is_numeric($name)) {
375 return 'The cookie name must not be empty';
378 // Check if any of the invalid characters are present in the cookie name
380 '/[\x00-\x20\x22\x28-\x29\x2c\x2f\x3a-\x40\x5c\x7b\x7d\x7f]/',
383 return 'Cookie name must not contain invalid characters: ASCII '
384 . 'Control characters (0-31;127), space, tab and the '
385 . 'following characters: ()<>@,;:\"/?={}';
388 // Value must not be empty, but can be 0
389 $value = $this->getValue();
390 if (empty($value) && !is_numeric($value)) {
391 return 'The cookie value must not be empty';
394 // Domains must not be empty, but can be 0
395 // A "0" is not a valid internet domain, but may be used as server name
396 // in a private network.
397 $domain = $this->getDomain();
398 if (empty($domain) && !is_numeric($domain)) {
399 return 'The cookie domain must not be empty';