Luminova Framework

PHP Luminova: Managing Cookies with a Cookie FileJar for HTTP Requests

Last updated: 2026-11-28 20:57:12

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. Set readOnly when the jar should be used without writing to disk.
  • Domain and path selection. Novio passes the request URL to the jar. Set both domain and path in the jar configuration to override URL-based selection. Entries are matched by exact domain and path.

When initializing or working with an array of cookies (e.g., in methods like newCookie or toNetscapeCookies), the array must follow this specific structure:

  1. Lowercase Option Keys:All cookie option keys should be in lowercase.

  2. Cookie Name as Key:The cookie name is used as the array key.

  3. Options as Nested Array:Cookie options are stored as a child array under the options key, while the value key 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']; // dark

Class Definition


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 is null.
  • domain (string|null): Specifies the domain for the cookie. If set, it overrides domain extraction from the request URL. Default is null.
  • path (string|null): Specifies the path for the cookie. If set, it overrides path extraction from the request URL. Default is null.
  • newSession (bool): Indicates whether the cookie starts a new session (uses PHP cURL's CURLOPT_COOKIESESSION). Default is false.
  • netscapeFormat (bool): Determines whether cookies are stored in Netscape format instead of a custom JSON format. Default is false.
  • readOnly (bool): If set to true, the cookie jar operates in read-only mode. Mutations can affect the in-memory jar, but skip disk writes. Defaults to false.
  • emulateBrowser (bool): Determines whether cookies should be handled in a way that mimics browser behavior. When set to true, cookies are sent using the Cookie header as part of the request headers (via CURLOPT_HTTPHEADER). If false, cookies are sent using the CURLOPT_COOKIE option in cURL. This can be useful for scenarios where specific header-based cookie handling is required to emulate browser-like interactions. Default is false.

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:

ParameterTypeDescription
$fromstring&#124;array<string,array<string,mixed>>The source of cookies, either a file path (string) or an array of cookies.
$configarray<string,mixed>Overrides for the jar configuration (default []).
$autoSaveboolWhether 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,
): CookieJarInterface

Parameters:

ParameterTypeDescription
$cookiesarray<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.
$configarray<string,mixed>Optional configurations or settings to apply to the
new or updated cookie (default []).
$autoSaveboolWhether 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 = []): self

Parameters:

ParameterTypeDescription
$namemixedThe name of the cookie.
$valuemixedThe value of the cookie.
$optionsarray<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): self

Parameters:

ParameterTypeDescription
$valuemixedThe value to set.

Return:

self - Return instance of Cookie Jar.

Throws:


setOptions

Set cookie options.

public function setOptions(CookieConfig|array $options): self

Parameters:

ParameterTypeDescription
$optionsCookieConfig&#124;array<string,mixed>An array of cookie options or cookie config class object.

Return:

self - Return instance of Cookie Jar.

Throws:


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): self

Parameters:

ParameterTypeDescription
$pathstringThe 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): self

Parameters:

ParameterTypeDescription
$domainstringThe 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): self

Parameters:

ParameterTypeDescription
$cookiesarray<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): array

Parameters:

ParameterTypeDescription
$namestringThe cookie name to retrieve.

Return:

array<string,mixed> - Returns the named entry, or an empty array if no entry matches.

KeyTypeDescription
valuemixedStored cookie value.
optionsarray<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(): CookieJarInterface

Return:

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): self

Parameters:

ParameterTypeDescription
$namestringName to select.

Return:

self - Returns the current jar for method chaining.


getCookies

Retrieves the entire cookies from the source.

public function getCookies(): array

Return:

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(): array

Return:

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 = []
): array

Parameters:

ParameterTypeDescription
$headersstring[]An array of Set-Cookie header strings to parse.
$rawboolWhether to handle cookies as raw values (default: false).
$defaultarray<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 = []
): array

Parameters:

ParameterTypeDescription
$cookiesarray<string,mixed>The request cookie map, typically $_COOKIE.
$rawboolWhether to handle cookies as raw values (default: false).
$defaultarray<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(): ?string

Return:

string|null - Return the cookie filepath and filename or null.


getConfig

Retrieves the cookie configuration options.

public function getConfig(): array

Return:

array<string,mixed> - Returns the jar’s configuration. Constructor overrides are included.

KeyTypeDescription
namestring&#124;nullSelected cookie name.
domainstring&#124;nullConfigured domain override.
pathstring&#124;nullConfigured path override.
newSessionboolWhether to request a new cURL cookie session.
netscapeFormatboolWhether to use Netscape storage.
readOnlyboolWhether to skip disk writes.
emulateBrowserboolWhether 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 = '/'): array

Parameters:

ParameterTypeDescription
$domainstringThe domain to filter cookies.
$pathstringThe 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:


getCookieStringByDomain

Retrieve cookies for a specific domain and path as a formatted string.

public function getCookieStringByDomain(?string $url = null, bool $metadata = false): ?string

Parameters:

ParameterTypeDescription
$url?stringThe request URL to extract domain and path.
If null, defaults to set domain (setCookieDomain) and path (setCookiePath).
$metadataboolWhether 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:


getName

Get the cookie name if specified.

public function getName(): ?string

Return:

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(): array

Return:

array<string,mixed> - Returns the stored options for the selected cookie. See the cookie array example for commonly used keys.

Throws:


getOption

Get an option value associated with the cookie name

public function getOption(string $key): mixed

Parameters:

ParameterTypeDescription
$keystringThe option key name to retrieve.

Return:

mixed - Return the option value associated with the cookie-option key.

Throws:


getValue

Get the cookie value if name is specified.

public function getValue(bool $asArray = false): mixed

Parameters:

ParameterTypeDescription
$asArrayboolWhether 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:


getDomain

Get the domain associated with the cookie, if name is specified.

public function getDomain(): string

Return:

string - Return the domain associated with the cookie.

Throws:


getPrefix

Get the prefix associated with the cookie.

public function getPrefix(): string

Return:

string - Returns the configured prefix, or an empty string if absent.

Return the prefix associated with the cookie.

Throws:


getMaxAge

Get the maximum age of the cookie.

public function getMaxAge(): int

Return:

int - Returns the remaining lifetime of the selected cookie in seconds.

Throws:


getPath

Get the path associated with the cookie.

public function getPath(): string

Return:

string - The path associated with the cookie.

Throws:


getSameSite

Get the SameSite attribute of the cookie.

public function getSameSite(): string

Return:

string - Return the SameSite attribute of the cookie.

Throws:


getPrefixedName

Get the prefixed name of the cookie.

public function getPrefixedName(): string

Return:

string - Return the prepended prefix name of the cookie.

Throws:


getExpiry

Get the cookie expiration time.

public function getExpiry(bool $returnString = false): int|string

Parameters:

ParameterTypeDescription
$returnStringboolWhether to retrieve unix-timestamp or formate cookie datetime string

Return:

int|string - Return cookie expiration timestamp or formatted string presentation.

Throws:


count

Count the number of cookies in storage.

public function count(): int

Return:

int - Return the number of cookies in storage.


size

Calculates the total size of all cookies in bytes.

public function size(): int

Return:

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): bool

Parameters:

ParameterTypeDescription
$namestringThe 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): bool

Parameters:

ParameterTypeDescription
$name?stringName 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(): bool

Return:

bool - Return true if the cookie was cleared, false otherwise.


delete

Remove a cookie by name.

public function delete(?string $name = null): bool

Parameters:

ParameterTypeDescription
$name?stringName 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): bool

Parameters:

ParameterTypeDescription
$name?stringCookie 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(): bool

Return:

bool - Return true if the cookie is secure, false otherwise.

Throws:


isHttpOnly

Check if the cookie is HTTP-only.

public function isHttpOnly(): bool

Return:

bool - Return true if the cookie is HTTP-only, false otherwise.

Throws:


isRaw

Check if the cookie value is raw.

public function isRaw(): bool

Return:

bool - Return true if the cookie value is raw, false otherwise.

Throws:


isExpired

Check if the cookie has expired.

public function isExpired(): bool

Return:

bool - Return true if the cookie has expired otherwise false.

Throws:


isSubdomains

Check whether the cookie include subdomains.

public function isSubdomains(): bool

Return:

bool - Return true if subdomain is included, false otherwise.

Throws:

isEmpty

Checks if the cookie jar is empty.

public function isEmpty(): bool

Return:

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(): bool

Return:

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(): bool

Return:

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(): bool

Return:

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(): bool

Return:

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): string

Parameters:

ParameterTypeDescription
$metadataboolWhether to include cookie attributes (default false).

Return:

string - Return the header string representation of the Cookie object.

Throws:

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=Lax

toArray

Convert the current cookie name to an array.

public function toArray(): array

Return:

array<string,mixed> - Returns the selected cookie data, with its stored options merged into the same array.

KeyTypeDescription
namestring&#124;nullSelected cookie name.
valuemixedSelected cookie value.

Throws:


toNetscapeCookies

Converts an array of cookies to a Netscape-formatted cookie file string.

public function toNetscapeCookies(?array $cookies = null): string

Parameters:

ParameterTypeDescription
$cookiesarray<string,array<string,mixed>>&#124;nullAn 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   jal8an935c

Note: 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(): bool

Return:

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(): mixed

Return:

array<array-key,mixed> - Returns the data passed to the JSON encoder.