Class Cookie
Cookie object to build a cookie and turn it into a header value
An HTTP cookie (also called web cookie, Internet cookie, browser cookie or simply cookie) is a small piece of data sent from a website and stored on the user's computer by the user's web browser while the user is browsing.
Cookies were designed to be a reliable mechanism for websites to remember stateful information (such as items added in the shopping cart in an online store) or to record the user's browsing activity (including clicking particular buttons, logging in, or recording which pages were visited in the past). They can also be used to remember arbitrary pieces of information that the user previously entered into form fields such as names, and preferences.
Cookie objects are immutable, and you must re-assign variables when modifying cookie objects:
$cookie = $cookie->withValue('0');See: \Cake\Http\Cookie\CookieCollection for working with collections of cookies.
See: \Cake\Http\Response::getCookieCollection() for working with response cookies.
Link: https://tools.ietf.org/html/draft-ietf-httpbis-rfc6265bis-03
Link: https://en.wikipedia.org/wiki/HTTP_cookie
Constants
- 
          
          stringEXPIRES_FORMAT ¶'D, d-M-Y H:i:s T'Expires attribute format. 
- 
          
          stringSAMESITE_LAX ¶'Lax'SameSite attribute value: Lax 
- 
          
          stringSAMESITE_NONE ¶'None'SameSite attribute value: None 
- 
          
          stringSAMESITE_STRICT ¶'Strict'SameSite attribute value: Strict 
- 
          
          array<string>SAMESITE_VALUES ¶[self::SAMESITE_LAX, self::SAMESITE_STRICT, self::SAMESITE_NONE]Valid values for "SameSite" attribute. 
Property Summary
- 
        $defaults protected staticarray<string, mixed>Default attributes for a cookie. 
- 
        $domain protectedstringDomain 
- 
        $expiresAt protectedDateTime|DateTimeImmutable|nullExpiration time 
- 
        $httpOnly protectedboolHTTP only 
- 
        $isExpanded protectedboolWhether a JSON value has been expanded into an array. 
- 
        $name protectedstringCookie name 
- 
        $path protectedstringPath 
- 
        $sameSite protectedstring|nullSamesite 
- 
        $secure protectedboolSecure 
- 
        $value protectedarray|stringRaw Cookie value. 
Method Summary
- 
          __construct() publicConstructor 
- 
          _expand() protectedExplode method to return array from string set in CookieComponent::_flatten() Maintains reading backwards compatibility with 1.x CookieComponent::_flatten(). 
- 
          _flatten() protectedImplode method to keep keys are multidimensional arrays 
- 
          _setValue() protectedSetter for the value attribute. 
- 
          check() publicChecks if a value exists in the cookie data. 
- 
          create() public staticFactory method to create Cookie instances. 
- 
          createFromHeaderString() public staticCreate Cookie instance from "set-cookie" header string. 
- 
          dateTimeInstance() protected staticConverts non null expiry value into DateTimeInterface instance. 
- 
          getDomain() publicGet the domain attribute. 
- 
          getExpiresTimestamp() publicGet the timestamp from the expiration time 
- 
          getExpiry() publicGet the current expiry time 
- 
          getFormattedExpires() publicBuilds the expiration value part of the header string 
- 
          getId() publicGet the id for a cookie 
- 
          getName() publicGets the cookie name 
- 
          getOptions() publicGet cookie options 
- 
          getPath() publicGet the path attribute. 
- 
          getSameSite() publicGet the SameSite attribute. 
- 
          getScalarValue() publicGets the cookie value as scalar. 
- 
          getStringValue() public deprecatedGets the cookie value as a string. 
- 
          getValue() publicGets the cookie value 
- 
          isExpanded() publicChecks if the cookie value was expanded 
- 
          isExpired() publicCheck if a cookie is expired when compared to $time 
- 
          isHttpOnly() publicCheck if the cookie is HTTP only 
- 
          isSecure() publicCheck if the cookie is secure 
- 
          read() publicRead data from the cookie 
- 
          setDefaults() public staticSet default options for the cookies. 
- 
          toArray() publicGet cookie data as array. 
- 
          toHeaderValue() publicReturns a header value as string 
- 
          validateName() protectedValidates the cookie name 
- 
          validateSameSiteValue() protected staticCheck that value passed for SameSite is valid. 
- 
          withAddedValue() publicCreate a new cookie with updated data. 
- 
          withDomain() publicCreate a cookie with an updated domain 
- 
          withExpired() publicCreate a new cookie that will expire/delete the cookie from the browser. 
- 
          withExpiry() publicCreate a cookie with an updated expiration date 
- 
          withHttpOnly() publicCreate a cookie with HTTP Only updated 
- 
          withName() publicSets the cookie name 
- 
          withNeverExpire() publicCreate a new cookie that will virtually never expire. 
- 
          withPath() publicCreate a new cookie with an updated path 
- 
          withSameSite() publicCreate a cookie with an updated SameSite option. 
- 
          withSecure() publicCreate a cookie with Secure updated 
- 
          withValue() publicCreate a cookie with an updated value. 
- 
          withoutAddedValue() publicCreate a new cookie without a specific path 
Method Detail
__construct() ¶ public
__construct(string $name, array|string $value = '', DateTime|DateTimeImmutable|null $expiresAt = null, string|null $path = null, string|null $domain = null, bool|null $secure = null, bool|null $httpOnly = null, string|null $sameSite = null)Constructor
The constructors args are similar to the native PHP setcookie() method.
The only difference is the 3rd argument which excepts null or an
DateTime or DateTimeImmutable object instead an integer.
Parameters
- 
                string$name
- Cookie name 
- 
                array|string$value optional
- Value of the cookie 
- 
                DateTime|DateTimeImmutable|null$expiresAt optional
- Expiration time and date 
- 
                string|null$path optional
- Path 
- 
                string|null$domain optional
- Domain 
- 
                bool|null$secure optional
- Is secure 
- 
                bool|null$httpOnly optional
- HTTP Only 
- 
                string|null$sameSite optional
- Samesite 
Links
_expand() ¶ protected
_expand(string $string): array|stringExplode method to return array from string set in CookieComponent::_flatten() Maintains reading backwards compatibility with 1.x CookieComponent::_flatten().
Parameters
- 
                string$string
- A string containing JSON encoded data, or a bare string. 
Returns
array|stringMap of key and values
_flatten() ¶ protected
_flatten(array $array): stringImplode method to keep keys are multidimensional arrays
Parameters
- 
                array$array
- Map of key and values 
Returns
stringA JSON encoded string.
_setValue() ¶ protected
_setValue(array|string $value): voidSetter for the value attribute.
Parameters
- 
                array|string$value
- The value to store. 
Returns
voidcheck() ¶ public
check(string $path): boolChecks if a value exists in the cookie data.
This method will expand serialized complex data, on first use.
Parameters
- 
                string$path
- Path to check 
Returns
boolcreate() ¶ public static
create(string $name, array|string $value, array<string, mixed> $options = []): staticFactory method to create Cookie instances.
Parameters
- 
                string$name
- Cookie name 
- 
                array|string$value
- Value of the cookie 
- 
                array<string, mixed>$options optional
- Cookies options. 
Returns
staticSee Also
createFromHeaderString() ¶ public static
createFromHeaderString(string $cookie, array<string, mixed> $defaults = []): staticCreate Cookie instance from "set-cookie" header string.
Parameters
- 
                string$cookie
- Cookie header string. 
- 
                array<string, mixed>$defaults optional
- Default attributes. 
Returns
staticSee Also
dateTimeInstance() ¶ protected static
dateTimeInstance(mixed $expires): DateTime|DateTimeImmutable|nullConverts non null expiry value into DateTimeInterface instance.
Parameters
- 
                mixed$expires
- Expiry value. 
Returns
DateTime|DateTimeImmutable|nullgetExpiresTimestamp() ¶ public
getExpiresTimestamp(): int|nullGet the timestamp from the expiration time
Returns
int|nullgetExpiry() ¶ public
getExpiry(): DateTime|DateTimeImmutable|nullGet the current expiry time
Returns
DateTime|DateTimeImmutable|nullgetFormattedExpires() ¶ public
getFormattedExpires(): stringBuilds the expiration value part of the header string
Returns
stringgetId() ¶ public
getId(): stringGet the id for a cookie
Cookies are unique across name, domain, path tuples.
Returns
stringgetOptions() ¶ public
getOptions(): array<string, mixed>Get cookie options
Returns
array<string, mixed>getScalarValue() ¶ public
getScalarValue(): mixedGets the cookie value as scalar.
This will collapse any complex data in the cookie with json_encode()
Returns
mixedgetStringValue() ¶ public
getStringValue(): mixedGets the cookie value as a string.
This will collapse any complex data in the cookie with json_encode()
Returns
mixedisExpired() ¶ public
isExpired(DateTime|DateTimeImmutable $time = null): boolCheck if a cookie is expired when compared to $time
Cookies without an expiration date always return false.
Parameters
- 
                DateTime|DateTimeImmutable$time optional
Returns
boolread() ¶ public
read(string|null $path = null): mixedRead data from the cookie
This method will expand serialized complex data, on first use.
Parameters
- 
                string|null$path optional
- Path to read the data from 
Returns
mixedsetDefaults() ¶ public static
setDefaults(array<string, mixed> $options): voidSet default options for the cookies.
Valid option keys are:
- expires: Can be a UNIX timestamp or- strtotime()compatible string or- DateTimeInterfaceinstance or- null.
- path: A path string. Defauts to- '/'.
- domain: Domain name string. Defaults to- ''.
- httponly: Boolean. Defaults to- false.
- secure: Boolean. Defaults to- false.
- samesite: Can be one of- CookieInterface::SAMESITE_LAX,- CookieInterface::SAMESITE_STRICT,- CookieInterface::SAMESITE_NONEor- null. Defaults to- null.
Parameters
- 
                array<string, mixed>$options
- Default options. 
Returns
voidtoArray() ¶ public
toArray(): array<string, mixed>Get cookie data as array.
Returns
array<string, mixed>validateName() ¶ protected
validateName(string $name): voidValidates the cookie name
Parameters
- 
                string$name
- Name of the cookie 
Returns
voidThrows
InvalidArgumentExceptionLinks
validateSameSiteValue() ¶ protected static
validateSameSiteValue(string $sameSite): voidCheck that value passed for SameSite is valid.
Parameters
- 
                string$sameSite
- SameSite value 
Returns
voidThrows
InvalidArgumentExceptionwithAddedValue() ¶ public
withAddedValue(string $path, mixed $value): staticCreate a new cookie with updated data.
Parameters
- 
                string$path
- Path to write to 
- 
                mixed$value
- Value to write 
Returns
staticwithDomain() ¶ public
withDomain(string $domain): staticCreate a cookie with an updated domain
Parameters
- 
                string$domain
Returns
staticwithExpired() ¶ public
withExpired(): staticCreate a new cookie that will expire/delete the cookie from the browser.
This is done by setting the expiration time to 1 year ago
Returns
staticwithExpiry() ¶ public
withExpiry(DateTime|DateTimeImmutable $dateTime): staticCreate a cookie with an updated expiration date
Parameters
- 
                DateTime|DateTimeImmutable$dateTime
Returns
staticwithHttpOnly() ¶ public
withHttpOnly(bool $httpOnly): staticCreate a cookie with HTTP Only updated
Parameters
- 
                bool$httpOnly
Returns
staticwithName() ¶ public
withName(string $name): staticSets the cookie name
Parameters
- 
                string$name
Returns
staticwithNeverExpire() ¶ public
withNeverExpire(): staticCreate a new cookie that will virtually never expire.
Returns
staticwithPath() ¶ public
withPath(string $path): staticCreate a new cookie with an updated path
Parameters
- 
                string$path
Returns
staticwithSameSite() ¶ public
withSameSite(string|null $sameSite): staticCreate a cookie with an updated SameSite option.
Parameters
- 
                string|null$sameSite
Returns
staticwithSecure() ¶ public
withSecure(bool $secure): staticCreate a cookie with Secure updated
Parameters
- 
                bool$secure
Returns
staticwithValue() ¶ public
withValue(array|string $value): staticCreate a cookie with an updated value.
Parameters
- 
                array|string$value
Returns
staticwithoutAddedValue() ¶ public
withoutAddedValue(string $path): staticCreate a new cookie without a specific path
Parameters
- 
                string$path
- Path to remove 
Returns
static