PHP Luminova: Managing Cookies with a Cookie FileJar for HTTP Requests
The cookie file jar provides an easy way to manage cookies when making HTTP requests with the Luminova cURL client or retrieving an incoming HTTP request cookie header.
Use FileJar to keep cookies across outgoing HTTP requests with the Novio HTTP client. The jar can load an existing JSON or Netscape cookie file. It can also build cookie entries from response Set-Cookie headers or the incoming request’s $_COOKIE values.
Key Features
- Persistent storage. An array source uses the default cookie file under
writeable/tmp. Pass an existing file path to use a different file. SetreadOnlywhen the jar should be used without writing to disk. - Domain and path selection. Novio passes the request URL to the jar. Set both
domainandpathin the jar configuration to override URL-based selection. Entries are matched by exact domain and path.
Cookie Array Format
When initializing or working with an array of cookies (e.g., in methods like newCookie or toNetscapeCookies), the array must follow this specific structure:
Lowercase Option Keys:All cookie option keys should be in lowercase.
Cookie Name as Key:The cookie name is used as the array key.
Options as Nested Array:Cookie options are stored as a child array under the
optionskey, while thevaluekey holds the cookie's value.
Example
$cookies = [
"CookieName" => [
"value" => "64ke1i31a93f",
"options" => [
"prefix" => "optional-prefix",
"raw" => false,
"expires" => "Thu, 31 Oct 2080 16:12:50 GMT",
"path" => "/",
"domain" => ".example.com",
"secure" => true,
"httponly" => true,
"samesite" => "Lax"
]
],
//...
];This structure ensures consistency and compatibility across cookie-related operations.
Implementing Cookie Jar in an HTTP Request
Below is an example that demonstrates how to use the FileJar with Luminova Novio HTTP client class:
use Luminova\Cookies\FileJar;
use Luminova\Http\Message\Response;
use Luminova\Http\Network;
$jar = new FileJar([
'theme' => [
'value' => 'dark',
'options' => [
'domain' => 'example.com',
'path' => '/',
'expires' => gmdate(FileJar::EXPIRES_FORMAT, time() + 3600),
],
],
], ['readOnly' => true]);
$response = Network::get('https://example.com/', ['cookies' => $jar]);
if ($response instanceof Response && $response->cookie !== null) {
foreach ($response->cookie->getCookieNames() as $name) {
$entry = $response->cookie->get($name);
echo $name . '=' . $entry['value'] . PHP_EOL;
}
}
echo $response->getBody()->getContents();Persist Cookies in a JSON File
Pass an existing JSON file to use a custom storage path. This example assumes the parent directory exists.
use Luminova\Cookies\FileJar;
$path = root('/writeable/tmp/', 'example-cookies.json');
if (!is_file($path)) {
file_put_contents($path, '{}');
}
$jar = new FileJar($path);
$jar->set('theme', 'dark', [
'domain' => 'example.com',
'path' => '/',
]);
$reopened = new FileJar($path);
echo $reopened->get('theme')['value']; // darkClass Definition
- Class namespace:
Luminova\Cookies\FileJar - This class implements:Luminova\Interface\CookieJarInterface, Luminova\Interface\ArrayableInterface, \Stringable, \Countable
Methods
Initialization Configuration
This property defines customizable initialization options for handling cookies, such as their name, domain, path, and storage preferences. These settings influence how cookies are managed and stored during a session or across requests.
Configuration Keys:
- name
(string|null): Sets the default cookie name to manage. The cookie's name. Can also be set after initialization. Default isnull. - domain
(string|null): Specifies the domain for the cookie. If set, it overrides domain extraction from the request URL. Default isnull. - path
(string|null): Specifies the path for the cookie. If set, it overrides path extraction from the request URL. Default isnull. - newSession
(bool): Indicates whether the cookie starts a new session (uses PHP cURL'sCURLOPT_COOKIESESSION). Default isfalse. - netscapeFormat
(bool): Determines whether cookies are stored in Netscape format instead of a custom JSON format. Default isfalse. - readOnly
(bool): If set totrue, the cookie jar operates in read-only mode. Mutations can affect the in-memory jar, but skip disk writes. Defaults tofalse. - emulateBrowser
(bool): Determines whether cookies should be handled in a way that mimics browser behavior. When set totrue, cookies are sent using theCookieheader as part of the request headers (viaCURLOPT_HTTPHEADER). Iffalse, cookies are sent using theCURLOPT_COOKIEoption in cURL. This can be useful for scenarios where specific header-based cookie handling is required to emulate browser-like interactions. Default isfalse.
Example usage of cookie configuration:
$cookieJar = new FileJar('path/to/cookie.txt', [
'name' => 'SessionID',
'domain' => '.example.com',
'path' => '/',
'newSession' => false,
'netscapeFormat' => false,
'readOnly' => false,
'emulateBrowser' => false,
]);constructor
Constructor to initialize cookies from a file path or an array.
public function __construct(
string|array $from,
array $config = [],
bool $autoSave = true
)Parameters:
| Parameter | Type | Description |
|---|---|---|
$from | string|array<string,array<string,mixed>> | The source of cookies, either a file path (string) or an array of cookies. |
$config | array<string,mixed> | Overrides for the jar configuration (default []). |
$autoSave | bool | Whether to save non-empty array input during construction (default true). Later mutations can still write to the file. |
If a string is provided, it is treated as a file path, and cookies are loaded from the file.If an array is provided, it is directly used as the cookies array.
newCookie
Create a new cookie instance.
public static function newCookie(
array $cookies,
array $config = [],
bool $autoSave = true,
): CookieJarInterfaceParameters:
| Parameter | Type | Description |
|---|---|---|
$cookies | array<string,array<string,mixed>> | An associative array of cookies where the key is the cookie name and the value contains the cookie data and options. |
$config | array<string,mixed> | Optional configurations or settings to apply to the new or updated cookie (default []). |
$autoSave | bool | Whether to save non-empty input during construction (default true). |
Return:
CookieJarInterface - Returns a new jar initialized from the supplied entries.
Example:
Define cookies:
$cookies = [
'SessionID' => [
'value' => 'abc123',
'options' => [
'path' => '/',
'domain' => '.example.com',
'secure' => true,
'httponly' => true,
'samesite' => 'Lax',
],
]
];
$cookieJar = FileJar::newCookie($cookies, [
'netscapeFormat' => true,
'readOnly' => true,
]);
// Retrieve a specific cookie
$cookie = $cookieJar->setCookie('SessionID')
->getCookie();
echo "Name: SessionID, Value: {$cookie->getValue()}";set
Set a cookie value by name. Supply a non-empty domain in the options.
public function set(mixed $name, mixed $value, array $options = []): selfParameters:
| 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:
self - Return instance of Cookie Jar.
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 instance of Cookie Jar.
Throws:
- Luminova\Exceptions\CookieException - Throws if called without cookie name specified.
setOptions
Set cookie options.
public function setOptions(CookieConfig|array $options): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$options | CookieConfig|array<string,mixed> | An array of cookie options or cookie config class object. |
Return:
self - Return instance of Cookie Jar.
Throws:
- Luminova\Exceptions\CookieException - Throws if called without cookie name specified.
setCookiePath
Set a custom path for retrieving request cookies.
This path will be used when filtering cookies instead of extracting the path from a request URL.
public function setCookiePath(string $path): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$path | string | The custom path to set. |
Return:
self - Returns the current instance for method chaining.
Note: If set a custom cookie request path, you must also set domain
setCookieDomain.
setCookieDomain
Set a custom domain for retrieving request cookies.
public function setCookieDomain(string $domain): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$domain | string | The custom domain to set. |
Return:
self - Return instance of Cookie Jar.
This domain will be used when filtering cookies instead of extracting the domain from a request URL.
Note: If set a custom cookie request domain, you must also set path
setCookiePath.
setCookies
Merge entries into the jar. Entries with the same name are replaced.
public function setCookies(array $cookies): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$cookies | array<string,array<string,mixed>> | Cookie entries keyed by name. |
Return:
self - Return instance of Cookie Jar.
get
Retrieve a cookie entry by name.
public function get(string $name): arrayParameters:
| Parameter | Type | Description |
|---|---|---|
$name | string | The cookie name to retrieve. |
Return:
array<string,mixed> - Returns the named entry, or an empty array if no entry matches.
| Key | Type | Description |
|---|---|---|
value | mixed | Stored cookie value. |
options | array<string,mixed> | Options stored for the cookie. |
getCookie
Create a separate jar containing the currently selected cookie. Call setCookie() to select a name first when the jar contains multiple cookies.
public function getCookie(): CookieJarInterfaceReturn:
CookieJarInterface - Returns a new jar containing the selected entry.
Example:
Manage Cookie By Name:
$cookie = $cookieJar->setCookie('my-cookie')->getCookie();
echo $cookie->getPrefix();
echo $cookie->getDomain();
echo $cookie->toString();setCookie
Select a cookie name for subsequent access through methods such as getValue() and getOptions().
public function setCookie(string $name): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$name | string | Name to select. |
Return:
self - Returns the current jar for method chaining.
getCookies
Retrieves the entire cookies from the source.
public function getCookies(): arrayReturn:
array<string,array<string,mixed>> - Return an associative array of cookies where keys are the cookie names. See the cookie array format above.
If cookies have already been loaded, they are returned directly.If a file path is provided, the cookies are loaded from the file.If no file path is provided, an empty array is returned.
getCookieNames
Retrieves an array of all cookie names in cookie jar.
public function getCookieNames(): arrayReturn:
array<int,string|int> - Returns the loaded cookie names. PHP represents numeric array keys as integers.
parseFromHeader
Parse and retrieve cookies from Set-Cookie header values.
public static function parseFromHeader(
array $headers,
bool $raw = false,
array $default = []
): arrayParameters:
| Parameter | Type | Description |
|---|---|---|
$headers | string[] | An array of Set-Cookie header strings to parse. |
$raw | bool | Whether to handle cookies as raw values (default: false). |
$default | array<string,mixed> | Default options (default []). Include a non-empty domain when the input does not supply one. |
Return:
array<string,array<string,mixed>> - Return an associative array of extracted cookies, where the key is the cookie name and the value contains the cookie data and options. See the cookie array format above.
Example:
Set cookies from header
$headers = [
"SessionID=abc123; Path=/; HttpOnly",
"UserID=42; Secure; Max-Age=3600",
];
$defaultOptions = [
'domain' => 'example.com',
];
// Parse cookies from headers
$cookies = FileJar::parseFromHeader($headers, false, $defaultOptions);
$newCookieJar = new FileJar($cookies, [
'readOnly' => true
]);
echo $newCookieJar->setCookie('SessionID')->getCookie()->getValue();parseFromGlobal
Parse and retrieve cookies from global variable $_COOKIE values.
public static function parseFromGlobal(
array $cookies,
bool $raw = false,
array $default = []
): arrayParameters:
| Parameter | Type | Description |
|---|---|---|
$cookies | array<string,mixed> | The request cookie map, typically $_COOKIE. |
$raw | bool | Whether to handle cookies as raw values (default: false). |
$default | array<string,mixed> | Default options (default []). Include a non-empty domain when the input does not supply one. |
Return:
array<string,array<string,mixed>> - Return an associative array of extracted cookies, where the key is the cookie name and the value contains the cookie data and options. See the cookie array format above.
Example:
Set cookies from header
$cookies = [
"SessionID" => "abc123",
"UserID" => 42,
];
$defaultOptions = [
'domain' => 'example.com',
];
// Parse cookies from global
$cookies = FileJar::parseFromGlobal($cookies, false, $defaultOptions);
// To use incoming cookies, pass $_COOKIE as the first argument.
$newCookieJar = new FileJar($cookies, [
'readOnly' => true
]);
echo $newCookieJar->setCookie('SessionID')
->getCookie()
->getValue();getCookieFile
Retrieves the cookie storage jar filename.
public function getCookieFile(): ?stringReturn:
string|null - Return the cookie filepath and filename or null.
getConfig
Retrieves the cookie configuration options.
public function getConfig(): arrayReturn:
array<string,mixed> - Returns the jar’s configuration. Constructor overrides are included.
| Key | Type | Description |
|---|---|---|
name | string|null | Selected cookie name. |
domain | string|null | Configured domain override. |
path | string|null | Configured path override. |
newSession | bool | Whether to request a new cURL cookie session. |
netscapeFormat | bool | Whether to use Netscape storage. |
readOnly | bool | Whether to skip disk writes. |
emulateBrowser | bool | Whether Novio sends an explicit Cookie header. |
getCookieByDomain
Retrieve all cookies for a specific domain and path. Only unexpired cookies are returned.
public function getCookieByDomain(string $domain, string $path = '/'): arrayParameters:
| Parameter | Type | Description |
|---|---|---|
$domain | string | The domain to filter cookies. |
$path | string | The path to filter cookies. Defaults to '/'. |
Return:
array<string,array<string,mixed>> - Returns entries whose domain and path match exactly. See the cookie array format above.
Throws:
- Luminova\Exceptions\CookieException - If the domain is empty.
getCookieStringByDomain
Retrieve cookies for a specific domain and path as a formatted string.
public function getCookieStringByDomain(?string $url = null, bool $metadata = false): ?stringParameters:
| Parameter | Type | Description |
|---|---|---|
$url | ?string | The request URL to extract domain and path. If null, defaults to set domain ( setCookieDomain) and path (setCookiePath). |
$metadata | bool | Whether to include cookie attributes (default false). |
Return:
string|null - Return a semicolon-separated cookie string, or null if no cookies match.
Only unexpired cookies are included.
Throws:
- Luminova\Exceptions\CookieException - If no valid domain is found or set.
getName
Get the cookie name if specified.
public function getName(): ?stringReturn:
string|null - Returns the selected cookie name, or null if no name is selected.
getOptions
Get the options associated with the cookie name if name is specified.
public function getOptions(): arrayReturn:
array<string,mixed> - Returns the stored options for the selected cookie. See the cookie array example for commonly used keys.
Throws:
- Luminova\Exceptions\CookieException - Throws if called without cookie name specified.
getOption
Get an option value associated with the cookie name
public function getOption(string $key): mixedParameters:
| Parameter | Type | Description |
|---|---|---|
$key | string | The option key name to retrieve. |
Return:
mixed - Return the option value associated with the cookie-option key.
Throws:
- Luminova\Exceptions\CookieException - Throws if called without cookie name specified.
getValue
Get the cookie value if name is specified.
public function getValue(bool $asArray = false): mixedParameters:
| Parameter | Type | Description |
|---|---|---|
$asArray | bool | Whether to decode a JSON string using associative arrays for JSON objects (default false). JSON scalars retain their decoded scalar types. |
Return:
mixed - Return the value of the cookie.
Throws:
- Luminova\Exceptions\CookieException - Throws if called without cookie name specified.
getDomain
Get the domain associated with the cookie, if name is specified.
public function getDomain(): stringReturn:
string - Return the domain associated with the cookie.
Throws:
- Luminova\Exceptions\CookieException - Throws if called without cookie name specified.
getPrefix
Get the prefix associated with the cookie.
public function getPrefix(): stringReturn:
string - Returns the configured prefix, or an empty string if absent.
Return the prefix associated with the cookie.
Throws:
- Luminova\Exceptions\CookieException - Throws if called without cookie name specified.
getMaxAge
Get the maximum age of the cookie.
public function getMaxAge(): intReturn:
int - Returns the remaining lifetime of the selected cookie in seconds.
Throws:
- Luminova\Exceptions\CookieException - Throws if called without cookie name specified.
getPath
Get the path associated with the cookie.
public function getPath(): stringReturn:
string - The path associated with the cookie.
Throws:
- Luminova\Exceptions\CookieException - Throws if called without cookie name specified.
getSameSite
Get the SameSite attribute of the cookie.
public function getSameSite(): stringReturn:
string - Return the SameSite attribute of the cookie.
Throws:
- Luminova\Exceptions\CookieException - Throws if called without cookie name specified.
getPrefixedName
Get the prefixed name of the cookie.
public function getPrefixedName(): stringReturn:
string - Return the prepended prefix name of the cookie.
Throws:
- Luminova\Exceptions\CookieException - Throws if called without cookie name specified.
getExpiry
Get the cookie expiration time.
public function getExpiry(bool $returnString = false): int|stringParameters:
| Parameter | Type | Description |
|---|---|---|
$returnString | bool | Whether to retrieve unix-timestamp or formate cookie datetime string |
Return:
int|string - Return cookie expiration timestamp or formatted string presentation.
Throws:
- Luminova\Exceptions\CookieException - Throws if called without cookie name specified.
count
Count the number of cookies in storage.
public function count(): intReturn:
int - Return the number of cookies in storage.
size
Calculates the total size of all cookies in bytes.
public function size(): intReturn:
int - Return total size of the cookies in bytes.
This method iterates through all cookies in the jar, calculates their size in bytes, and caches the result to avoid redundant recalculations. The size includes the name-value pairs for each cookie.
has
Check if a cookie with name exists.
public function has(string $name): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$name | string | The key of the cookie to check. |
Return:
bool - Return true if the cookie name exists, false otherwise.
hasPrefix
Check if a cookie name has a prefix.
public function hasPrefix(?string $name = null): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$name | ?string | Name to check. null uses the selected cookie name. |
Return:
bool - Returns true when the name begins with __Secure- or __Host-.
clear
Clear the entire cookie stored in file jar.
public function clear(): boolReturn:
bool - Return true if the cookie was cleared, false otherwise.
delete
Remove a cookie by name.
public function delete(?string $name = null): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$name | ?string | Name to remove. null uses the selected cookie name. |
Return:
bool - Return true if the cookie was removed, false otherwise.
forceExpire
Force mark a cookie as expired.
public function forceExpire(?string $name = null): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$name | ?string | Cookie to expire. null uses the currently selected name (default null). |
Return:
bool - Return true if cookie has expired, otherwise false.
isSecure
Check if the cookie is secure.
public function isSecure(): boolReturn:
bool - Return true if the cookie is secure, false otherwise.
Throws:
- Luminova\Exceptions\CookieException - Throws if called without cookie name specified.
isHttpOnly
Check if the cookie is HTTP-only.
public function isHttpOnly(): boolReturn:
bool - Return true if the cookie is HTTP-only, false otherwise.
Throws:
- Luminova\Exceptions\CookieException - Throws if called without cookie name specified.
isRaw
Check if the cookie value is raw.
public function isRaw(): boolReturn:
bool - Return true if the cookie value is raw, false otherwise.
Throws:
- Luminova\Exceptions\CookieException - Throws if called without cookie name specified.
isExpired
Check if the cookie has expired.
public function isExpired(): boolReturn:
bool - Return true if the cookie has expired otherwise false.
Throws:
- Luminova\Exceptions\CookieException - Throws if called without cookie name specified.
isSubdomains
Check whether the cookie include subdomains.
public function isSubdomains(): boolReturn:
bool - Return true if subdomain is included, false otherwise.
Throws:
- Luminova\Exceptions\CookieException - Throws if called without cookie name specified.
isEmpty
Checks if the cookie jar is empty.
public function isEmpty(): boolReturn:
bool - Returns true if the cookie jar is empty, false otherwise.
This method determines whether the cookie jar contains any cookies.It returns true if there are no cookies stored, and false otherwise.
isReadOnly
Checks if the cookie jar configuration is set to read-only mode.
public function isReadOnly(): boolReturn:
bool - Returns true if the cookie jar is read-only, otherwise false.
Determines whether the cookie jar is in read-only mode, preventing any modifications or persistent storage of cookies. This behavior is controlled by the readOnly configuration key during initialization.
isNewSession
Check whether cookie configuration is marked as a new session.
public function isNewSession(): boolReturn:
bool - Return true if marked as a new session, false otherwise.
See Also:
- https://www.php.net/manual/en/function.curl-setopt.php
isNetscapeCookie
Check whether cookie configuration is set to be read and write as netscape cookie format.
public function isNetscapeCookie(): boolReturn:
bool - Return true if the cookie should be in netscape cookie format, false otherwise.
isEmulateBrowser
Check whether cookie configuration is set to emulate browser behavior during requests, by setting cookies in the request header object Cookie instead of CURLOPT_COOKIE.
public function isEmulateBrowser(): boolReturn:
bool - Return true if should emulate browser, false otherwise.
toString
Serialize the selected cookie. Pass true to include attributes such as Path and SameSite. To retrieve a request cookie string for a URL, use getCookieStringByDomain().
public function toString(bool $metadata = false): stringParameters:
| Parameter | Type | Description |
|---|---|---|
$metadata | bool | Whether to include cookie attributes (default false). |
Return:
string - Return the header string representation of the Cookie object.
Throws:
- Luminova\Exceptions\CookieException - Throws if called without cookie name specified.
Example:
use Luminova\Cookies\FileJar;
$cookieJar = new FileJar([
'theme' => [
'value' => 'dark',
'options' => [
'domain' => 'example.com',
'path' => '/',
'httponly' => true,
'samesite' => 'Lax',
],
],
], ['readOnly' => true]);
echo $cookieJar->toString(true);Output:
theme=dark; Path=/; Domain=example.com; HttpOnly; SameSite=LaxtoArray
Convert the current cookie name to an array.
public function toArray(): arrayReturn:
array<string,mixed> - Returns the selected cookie data, with its stored options merged into the same array.
| Key | Type | Description |
|---|---|---|
name | string|null | Selected cookie name. |
value | mixed | Selected cookie value. |
Throws:
- Luminova\Exceptions\CookieException - Throws if called without cookie name specified.
toNetscapeCookies
Converts an array of cookies to a Netscape-formatted cookie file string.
public function toNetscapeCookies(?array $cookies = null): stringParameters:
| Parameter | Type | Description |
|---|---|---|
$cookies | array<string,array<string,mixed>>|null | An optional array of cookies to convert. If null, uses the instance's cookies. Each cookie should be an associative array with 'value' and 'options' keys. |
Return:
string - Return a string containing the Netscape-formatted cookies, or an empty string if no cookies are available.
This method generates a string representation of cookies in the Netscape cookie file format.An empty jar produces an empty string.
Example:
Convert all loaded cookies or specified cookies to netscape-formatted cookies.
echo $cookieJar->toNetscapeCookies();Output:
.example.com TRUE / TRUE 3497616770 PHPSESSID jal8an935cNote: The specified cookies must adhere to the cookie array format as described above
commit
Save the current cookie data to the configured file. Use this after constructing a jar with autoSave: false if you want to persist the initial entries explicitly.
public function commit(): boolReturn:
bool - Returns true if the save succeeds, or false if it fails. A read-only jar with a configured path returns true without writing.
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.