PHP Luminova: Reading and Setting HTTP Cookies
Set and read HTTP cookies with configurable expiration, path, domain, and security attributes.
Luminova's Cookie manager provides a convenient way to store data on the client-side, offering greater flexibility in managing cookie data compared to the SessionManager and CookieManager classes. With the Cookie class, you have the ability to configure the security access of the stored information according to your specific requirements.
The Cookie class stores data directly on the client-side, within cookies. This approach is particularly useful for scenarios where client-side storage is preferred or necessary, such as persisting user preferences, session tokens, or other application-specific data.
Usage
Write a preference cookie before sending any response body. An empty value allows you to create an instance to read a cookie already present in the request.
use Luminova\Cookies\Cookie;
$options = [
'expires' => time() + 3600,
'path' => '/',
'httponly' => true,
'samesite' => Cookie::LAX,
];
$theme = new Cookie('theme', 'dark', $options);
echo $theme->get(); // darkIn a later request, (new Cookie('theme'))->get() reads the incoming value. Use getValue() to read the value held by the instance.
Class Definition
- Class namespace:
Luminova\Cookies\Cookie - This class implements:Luminova\Interface\CookieInterface, Luminova\Interface\ArrayableInterface, \Stringable
Properties
options
The normalized options supplied at construction or through setOptions(). The table describes the framework defaults in Cookie::DEFAULT_OPTIONS.
/**
* @var array<string, mixed>
*/
protected array $options = [];Properties
| Name | Type | Description |
|---|---|---|
prefix | string | Cookie name prefix. Defaults to an empty string. |
expires | int | Expiration timestamp. Defaults to 0 for a session cookie. |
path | string | Cookie path. Defaults to /. |
domain | string | Cookie domain. Defaults to an empty string. |
secure | bool | Restricts transmission to HTTPS when enabled. Defaults to false. |
httponly | bool | Prevents script access when enabled. Defaults to true. |
samesite | string | SameSite policy. Defaults to Lax. |
raw | bool | Controls use of the raw cookie value. Defaults to false. |
Constants
These constants define common cookie attributes and formatting options used for setting and managing cookies.
| Constant | Type | Value | Description |
|---|---|---|---|
NONE | string | 'none' | Represents the SameSite=None policy, allowing cookies to be sent in all contexts, including cross-site requests. |
LAX | string | 'lax' | Represents the SameSite=Lax policy, allowing cookies in top-level navigations and some cross-site requests. |
STRICT | string | 'strict' | Represents the SameSite=Strict policy, restricting cookies to the same site only. |
Methods
constructor
Create a cookie object. Passing a non-empty value updates the request-local cookie data and attempts to send a cookie header.
public final function __construct(string $name, mixed $value = '', CookieConfig|array $options = [])Parameters:
| Parameter | Type | Description |
|---|---|---|
$name | string | Cookie name |
$value | mixed | cookie value (default ''). |
$options | CookieConfig|array<string,mixed> | Options array or an instance of App\Config\Cookie. Omitting the argument uses application configuration. Include expires in a custom options array. |
Throws:
- Luminova\Exceptions\CookieException - If the name, prefix, or SameSite attributes fail validation.
newFromString
Create a new Cookie instance from a Set-Cookie header.
public static function newFromString(
string $cookie,
bool $raw = false,
CookieConfig|array $options = []
): CookieInterfaceParameters:
| Parameter | Type | Description |
|---|---|---|
$cookie | string | The cookie header string. |
$raw | bool | Indicates if the cookie is raw (default false). |
$options | CookieConfig|array<string,mixed> | Default cookie options or an instance of App\Config\Cookie (default []). Supply expires when using an options array. |
Return:
CookieInterface - Return a new Cookie instance.
newFromArray
Create a cookie from an associative array or an object containing cookie data.
public static function newFromArray(
array|object $cookies,
CookieConfig|array $options = []
): CookieInterfaceParameters:
| Parameter | Type | Description |
|---|---|---|
$cookies | array<string,mixed>|object | Cookie data with a name, a value, and any additional options. |
$options | CookieConfig|array<string,mixed> | Default cookie options or an instance of App\Config\Cookie (default []). Supply expires when using an options array. |
Return:
CookieInterface - Return a new Cookie instance.
set
Set a cookie.
public function set(mixed $name, mixed $value, array $options = []): CookieInterfaceParameters:
| Parameter | Type | Description |
|---|---|---|
$name | mixed | The name of the cookie. |
$value | mixed | The value of the cookie. |
$options | array<string,mixed> | An array of cookie options. |
Return:
CookieInterface - Return new Cookie instance.
setValue
Set the value of a cookie.
public function setValue(mixed $value): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$value | mixed | The value to set. |
Return:
self - Return the instance of Cookie class.
setOptions
Set the options array used for subsequent writes. Set attributes at construction when you also need the attribute getters and toString() to reflect them.
public function setOptions(CookieConfig|array $options): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$options | CookieConfig|array<string,mixed> | Options array or an instance of App\Config\Cookie. Include an expires entry when supplying an options array. |
Return:
self - Return instance of Cookie class.
toString
Convert the cookie object to a string.
public function toString(): stringReturn:
string - The string representation of the Cookie object.
toArray
Convert the cookie to an array.
public function toArray(): arrayReturn:
array<string,mixed> - Returns the normalized options and current cookie data.
| Key | Type | Description |
|---|---|---|
name | string | Cookie name. |
value | mixed | Current instance value. |
prefix | string | Cookie name prefix. |
expires | int | Expiration timestamp. Zero indicates a session cookie. |
path | string | Cookie path. |
domain | string | Cookie domain. |
secure | bool | HTTPS-only flag. |
httponly | bool | Script-access restriction. |
samesite | string | SameSite policy. |
raw | bool | Raw-value flag. |
getString
Alias for toString().
public function getString(): stringReturn:
string - Returns the formatted cookie header value.
get
Retrieve the value of a cookie, if key is specified it will return value of the key .
public function get(?string $key = null): mixedParameters:
| Parameter | Type | Description |
|---|---|---|
$key | ?string | Optional key of the cookie to retrieve. |
Return:
mixed - Returns the cookie value.
getName
Get the name of the cookie.
public function getName(): stringReturn:
string - The name of the cookie.
getOptions
Get the options associated with the cookie.
public function getOptions(): arrayReturn:
array<string,mixed> - Returns normalized cookie options.
| Key | Type | Description |
|---|---|---|
prefix | string | Cookie name prefix. |
expires | int | Expiration timestamp. Zero indicates a session cookie. |
path | string | Cookie path. |
domain | string | Cookie domain. |
secure | bool | HTTPS-only flag. |
httponly | bool | Script-access restriction. |
samesite | string | SameSite policy. |
raw | bool | Raw-value flag. |
getValue
Get the value of the cookie.
public function getValue(): mixedReturn:
mixed - The value of the cookie.
getDomain
Get the domain associated with the cookie.
public function getDomain(): stringReturn:
string - The domain associated with the cookie.
getPrefix
Get the prefix associated with the cookie.
public function getPrefix(): stringReturn:
string - The prefix associated with the cookie.
getMaxAge
Get the maximum age of the cookie.
public function getMaxAge(): intReturn:
int - The maximum age of the cookie.
getPath
Get the path associated with the cookie.
public function getPath(): stringReturn:
string - The path associated with the cookie.
getSameSite
Get the SameSite attribute of the cookie.
public function getSameSite(): stringReturn:
string - The SameSite attribute of the cookie.
getId
Get the ID of the cookie.
public function getId(): stringReturn:
string - The ID of the cookie.
getPrefixedName
Get the prefixed name of the cookie.
public function getPrefixedName(): stringReturn:
string - The prepended prefix name of the cookie.
getExpiry
Get the cookie expiration time.
public function getExpiry(bool $returnString = false): int|stringParameters:
| Parameter | Type | Description |
|---|---|---|
$returnString | bool | Return cookie expiration timestamp or string presentation. |
Return:
int|string - The expiration time.
isSecure
Check if the cookie is secure.
public function isSecure(): boolReturn:
bool - True if the cookie is secure, false otherwise.
isHttpOnly
Check if the cookie is HTTP-only.
public function isHttpOnly(): boolReturn:
bool - True if the cookie is HTTP-only, false otherwise.
isRaw
Check if the cookie value is raw.
public function isRaw(): boolReturn:
bool - True if the cookie value is raw, false otherwise.
isExpired
Check if the cookie has expired.
public function isExpired(): boolReturn:
bool - Return true if the cookie has expired otherwise false.
hasPrefix
Check if a cookie name has a prefix.
public function hasPrefix(?string $name = null): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$name | ?string | The name of the cookie. |
Return:
bool - Returns true for a name starting with __Secure- or __Host-.
has
Check if a cookie exists, if key is passed NULL, it checks if the current cookie object name exists.
public function has(?string $key = null): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$key | ?string | The key of the cookie to check. |
Return:
bool - True if the cookie exists, false otherwise.
delete
Remove a cookie, If key is null or empty, delete the entire cookie.
public function delete(?string $key = null): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$key | ?string | The key of the cookie to remove. |
Return:
bool - Return true if the cookie was removed, false otherwise.
jsonSerialize
Provide the same array representation as __toArray() when encoding the object as JSON.
public function jsonSerialize(): mixedReturn:
array<array-key,mixed> - Returns the data passed to the JSON encoder.