Final Class Yiisoft\Cookies\Cookie
| Inheritance | Yiisoft\Cookies\Cookie |
|---|
Represents a cookie and also helps adding Set-Cookie header to response in order to set a cookie.
Public Methods
| Method | Description | Defined By |
|---|---|---|
| __construct() | Cookie constructor. | Yiisoft\Cookies\Cookie |
| __toString() | Returns the cookie as a header string. | Yiisoft\Cookies\Cookie |
| addToResponse() | Adds the cookie to the response and returns it. | Yiisoft\Cookies\Cookie |
| expire() | Returns modified cookie that will expire immediately. | Yiisoft\Cookies\Cookie |
| expireWhenBrowserIsClosed() | Will remove the expiration from the cookie which will convert the cookie to session cookie, which will expire as soon as the browser is closed. | Yiisoft\Cookies\Cookie |
| fromCookieString() | Parse Set-Cookie string and build Cookie object. |
Yiisoft\Cookies\Cookie |
| getDomain() | Gets the domain of the cookie. | Yiisoft\Cookies\Cookie |
| getExpires() | Gets the expiry of the cookie. | Yiisoft\Cookies\Cookie |
| getName() | Gets the name of the cookie. | Yiisoft\Cookies\Cookie |
| getPath() | Gets the path of the cookie. | Yiisoft\Cookies\Cookie |
| getSameSite() | Gets the SameSite attribute. | Yiisoft\Cookies\Cookie |
| getValue() | Gets the value of the cookie. | Yiisoft\Cookies\Cookie |
| isExpired() | Indicates whether the cookie is expired. | Yiisoft\Cookies\Cookie |
| isHttpOnly() | Whether the cookie can be accessed only through the HTTP protocol. | Yiisoft\Cookies\Cookie |
| isSecure() | Whether the cookie is secure. | Yiisoft\Cookies\Cookie |
| withDomain() | Creates a cookie copy with a new domain set. | Yiisoft\Cookies\Cookie |
| withExpires() | Creates a cookie copy with a new time the cookie expires. | Yiisoft\Cookies\Cookie |
| withHttpOnly() | Creates a cookie copy that would be accessible only through the HTTP protocol. | Yiisoft\Cookies\Cookie |
| withMaxAge() | Creates a cookie copy with a new lifetime set. | Yiisoft\Cookies\Cookie |
| withPath() | Creates a cookie copy with a new path set. | Yiisoft\Cookies\Cookie |
| withRawValue() | Creates a cookie copy with a new value that will not be encoded. | Yiisoft\Cookies\Cookie |
| withSameSite() | Creates a cookie copy with SameSite attribute. | Yiisoft\Cookies\Cookie |
| withSecure() | Creates a cookie copy by making it secure or insecure. | Yiisoft\Cookies\Cookie |
| withValue() | Creates a cookie copy with a new value. | Yiisoft\Cookies\Cookie |
Constants
| Constant | Value | Description | Defined By |
|---|---|---|---|
| PATTERN_TOKEN | '/^[a-zA-Z0-9!#$%&\' * +\- .^_`|~]+$/' | Regular Expression used to validate cookie name. | Yiisoft\Cookies\Cookie |
| SAME_SITE_LAX | 'Lax' |
SameSite policy Lax will prevent the cookie from being sent by the browser in all cross-site browsing contexts
during CSRF-prone request methods (e.g. POST, PUT, PATCH etc).
E.g. a POST request from https://otherdomain.com to https://yourdomain.com will not include the cookie,
however a GET request will.
When a user follows a link from https://otherdomain.com to https://yourdomain.com it will include the cookie.
This is the default value in modern browsers. |
Yiisoft\Cookies\Cookie |
| SAME_SITE_NONE | 'None' |
SameSite policy None cookies will be sent in all contexts, i.e. sending cross-origin is allowed.
None requires the Secure attribute in latest browser versions. |
Yiisoft\Cookies\Cookie |
| SAME_SITE_STRICT | 'Strict' |
SameSite policy Strict will prevent the cookie from being sent by the browser in all cross-site
browsing contexts regardless of the request method and even when following a regular link.
E.g. a GET request from https://otherdomain.com to https://yourdomain.com or a user following a link from
https://otherdomain.com to https://yourdomain.com will not include the cookie. |
Yiisoft\Cookies\Cookie |
Method Details
Cookie constructor.
| public mixed __construct ( string $name, string $value = '', DateTimeInterface|null $expires = null, string|null $domain = null, string|null $path = '/', boolean|null $secure = true, boolean|null $httpOnly = true, string|null $sameSite = self::SAME_SITE_LAX, boolean $encodeValue = true, \Psr\Clock\ClockInterface|null $clock = null ) | ||
| $name | string |
The name of the cookie. |
| $value | string |
The value of of the cookie. |
| $expires | DateTimeInterface|null |
The time the cookie expires. |
| $domain | string|null |
The path on the server in which cookie will be available on. |
| $path | string|null |
The host/domain that the cookie is available to. |
| $secure | boolean|null |
Whether the client should send back the cookie only over HTTPS connection. |
| $httpOnly | boolean|null |
Whether the cookie should be accessible only through the HTTP protocol. |
| $sameSite | string|null |
Whether the cookie should be available for cross-site requests. |
| $encodeValue | boolean |
Whether cookie value should be encoded. |
| $clock | \Psr\Clock\ClockInterface|null | |
| throws | InvalidArgumentException |
When one or more arguments are not valid. |
|---|---|---|
public function __construct(
string $name,
string $value = '',
?DateTimeInterface $expires = null,
?string $domain = null,
?string $path = '/',
?bool $secure = true,
?bool $httpOnly = true,
?string $sameSite = self::SAME_SITE_LAX,
bool $encodeValue = true,
?ClockInterface $clock = null
) {
if (!preg_match(self::PATTERN_TOKEN, $name)) {
throw new InvalidArgumentException("The cookie name \"$name\" contains invalid characters or is empty.");
}
$this->name = $name;
$this->value = $value;
$this->encodeValue = $encodeValue;
$this->expires = $expires !== null ? clone $expires : null;
$this->domain = $domain;
$this->setPath($path);
$this->secure = $secure;
$this->httpOnly = $httpOnly;
$this->setSameSite($sameSite);
$this->clock = $clock;
}
Returns the cookie as a header string.
| public string __toString ( ) | ||
| return | string |
The cookie header string. |
|---|---|---|
public function __toString(): string
{
$cookieParts = [
$this->name . '=' . ($this->encodeValue ? urlencode($this->value) : $this->value),
];
if ($this->expires !== null) {
$cookieParts[] = 'Expires=' . $this->expires->format(DateTimeInterface::RFC1123);
$cookieParts[] = 'Max-Age=' . ($this->expires->getTimestamp() - $this->getCurrentTimestamp());
}
if ($this->domain !== null) {
$cookieParts[] = 'Domain=' . $this->domain;
}
if ($this->path !== null) {
$cookieParts[] = 'Path=' . $this->path;
}
if ($this->secure) {
$cookieParts[] = 'Secure';
}
if ($this->httpOnly) {
$cookieParts[] = 'HttpOnly';
}
if ($this->sameSite !== null) {
$cookieParts[] = 'SameSite=' . $this->sameSite;
}
return implode('; ', $cookieParts);
}
Adds the cookie to the response and returns it.
| public \Psr\Http\Message\ResponseInterface addToResponse ( \Psr\Http\Message\ResponseInterface $response ) | ||
| $response | \Psr\Http\Message\ResponseInterface | |
| return | \Psr\Http\Message\ResponseInterface |
Response with added cookie. |
|---|---|---|
public function addToResponse(ResponseInterface $response): ResponseInterface
{
return $response->withAddedHeader(Header::SET_COOKIE, (string) $this);
}
Returns modified cookie that will expire immediately.
| public Yiisoft\Cookies\Cookie expire ( ) |
public function expire(): self
{
$new = clone $this;
$new->expires = $this->getCurrentTime()->modify('-1 year');
return $new;
}
Will remove the expiration from the cookie which will convert the cookie to session cookie, which will expire as soon as the browser is closed.
| public Yiisoft\Cookies\Cookie expireWhenBrowserIsClosed ( ) |
public function expireWhenBrowserIsClosed(): self
{
$new = clone $this;
$new->expires = null;
return $new;
}
Parse Set-Cookie string and build Cookie object.
| public static Yiisoft\Cookies\Cookie fromCookieString ( string $string, \Psr\Clock\ClockInterface|null $clock = null ) | ||
| $string | string |
|
| $clock | \Psr\Clock\ClockInterface|null | |
| throws | Exception | |
|---|---|---|
public static function fromCookieString(string $string, ?ClockInterface $clock = null): self
{
/** @psalm-var list<string> $rawAttributes */
$rawAttributes = preg_split('~\s*[;]\s*~', $string);
// array_filter with empty callback is used to filter out all falsy values.
$rawAttributes = array_filter($rawAttributes);
$rawAttribute = array_shift($rawAttributes);
if (!is_string($rawAttribute)) {
throw new InvalidArgumentException('Cookie string must have at least name.');
}
[$cookieName, $cookieValue] = self::splitCookieAttribute($rawAttribute);
/** @var array{name: string, value: string} $params */
$params = [
'name' => $cookieName,
'value' => $cookieValue !== null ? urldecode($cookieValue) : '',
];
while ($rawAttribute = array_shift($rawAttributes)) {
/** @var string $attributeKey */
[$attributeKey, $attributeValue] = self::splitCookieAttribute($rawAttribute);
$attributeKey = strtolower($attributeKey);
if ($attributeValue === null && !in_array($attributeKey, ['secure', 'httponly'], true)) {
continue;
}
$currentTimestamp = $clock === null ? time() : $clock->now()->getTimestamp();
/** @var string $attributeValue */
switch ($attributeKey) {
case 'expires':
$params['expires'] = new DateTimeImmutable($attributeValue);
break;
case 'max-age':
$params['expires'] = (new DateTimeImmutable())
->setTimestamp($currentTimestamp + (int) $attributeValue);
break;
case 'domain':
$params['domain'] = $attributeValue;
break;
case 'path':
$params['path'] = $attributeValue;
break;
case 'secure':
$params['secure'] = true;
break;
case 'httponly':
$params['httpOnly'] = true;
break;
case 'samesite':
$params['sameSite'] = $attributeValue;
break;
}
}
return new self(
$params['name'],
$params['value'],
$params['expires'] ?? null,
$params['domain'] ?? null,
$params['path'] ?? null,
$params['secure'] ?? null,
$params['httpOnly'] ?? null,
$params['sameSite'] ?? null,
true,
$clock
);
}
Gets the domain of the cookie.
| public string|null getDomain ( ) |
public function getDomain(): ?string
{
return $this->domain;
}
Gets the expiry of the cookie.
| public DateTimeImmutable|null getExpires ( ) |
public function getExpires(): ?DateTimeImmutable
{
if ($this->expires === null) {
return null;
}
// Can be replaced with DateTimeImmutable::createFromInterface in PHP 8.
return (new DateTimeImmutable())->setTimestamp($this->expires->getTimestamp());
}
Gets the name of the cookie.
| public string getName ( ) |
public function getName(): string
{
return $this->name;
}
Gets the path of the cookie.
| public string|null getPath ( ) |
public function getPath(): ?string
{
return $this->path;
}
Gets the SameSite attribute.
| public string|null getSameSite ( ) |
public function getSameSite(): ?string
{
return $this->sameSite;
}
Gets the value of the cookie.
| public string getValue ( ) |
public function getValue(): string
{
return $this->value;
}
Indicates whether the cookie is expired.
The cookie is expired when it has outdated Expires, or
zero or negative Max-Age attributes.
| public boolean isExpired ( ) | ||
| return | boolean |
Whether the cookie is expired. |
|---|---|---|
public function isExpired(): bool
{
return $this->expires !== null && $this->expires->getTimestamp() < $this->getCurrentTimestamp();
}
Whether the cookie can be accessed only through the HTTP protocol.
| public boolean isHttpOnly ( ) |
public function isHttpOnly(): bool
{
return $this->httpOnly ?? false;
}
Whether the cookie is secure.
| public boolean isSecure ( ) |
public function isSecure(): bool
{
return $this->secure ?? false;
}
Creates a cookie copy with a new domain set.
| public self withDomain ( string $domain ) | ||
| $domain | string | |
public function withDomain(string $domain): self
{
$new = clone $this;
$new->domain = $domain;
return $new;
}
Creates a cookie copy with a new time the cookie expires.
| public self withExpires ( DateTimeInterface $dateTime ) | ||
| $dateTime | DateTimeInterface | |
public function withExpires(DateTimeInterface $dateTime): self
{
$new = clone $this;
// Defensively clone the object to prevent further change
$new->expires = clone $dateTime;
return $new;
}
Creates a cookie copy that would be accessible only through the HTTP protocol.
| public self withHttpOnly ( boolean $httpOnly = true ) | ||
| $httpOnly | boolean | |
public function withHttpOnly(bool $httpOnly = true): self
{
$new = clone $this;
$new->httpOnly = $httpOnly;
return $new;
}
Creates a cookie copy with a new lifetime set.
If zero or negative interval is passed, the cookie will expire immediately.
| public Yiisoft\Cookies\Cookie withMaxAge ( DateInterval $interval ) | ||
| $interval | DateInterval |
Interval until the cookie expires. |
public function withMaxAge(DateInterval $interval): self
{
$new = clone $this;
$new->expires = $this->getCurrentTime()->add($interval);
return $new;
}
Creates a cookie copy with a new path set.
| public self withPath ( string $path ) | ||
| $path | string |
To be set for the cookie. |
public function withPath(string $path): self
{
$new = clone $this;
$new->setPath($path);
return $new;
}
Creates a cookie copy with a new value that will not be encoded.
| public self withRawValue ( mixed $value ) | ||
| $value | mixed |
String Value of the cookie. |
public function withRawValue(string $value): self
{
$new = clone $this;
$new->value = $value;
$new->encodeValue = false;
return $new;
}
Creates a cookie copy with SameSite attribute.
| public self withSameSite ( string $sameSite ) | ||
| $sameSite | string | |
public function withSameSite(string $sameSite): self
{
$new = clone $this;
$new->setSameSite($sameSite);
return $new;
}
Creates a cookie copy by making it secure or insecure.
| public Yiisoft\Cookies\Cookie withSecure ( boolean $secure = true ) | ||
| $secure | boolean |
Whether the cookie must be secure. |
public function withSecure(bool $secure = true): self
{
$new = clone $this;
$new->secure = $secure;
return $new;
}
Creates a cookie copy with a new value.
| public Yiisoft\Cookies\Cookie withValue ( mixed $value ) | ||
| $value | mixed |
String Value of the cookie. |
public function withValue(string $value): self
{
$new = clone $this;
$new->value = $value;
$new->encodeValue = true;
return $new;
}
Signup or Login in order to comment.