Primordyx Framework Documentation

Cookie
in package

Class Cookie

Handles encrypted, persistent client-side cookies using internal key-value storage.

This class stores multiple key-value pairs in a single encrypted cookie to:

  • Reduce cookie bloat (avoid hitting browser limits of ~50 cookies per domain)
  • Enhance security through AES-256-GCM encryption via Primordyx\Crypto
  • Provide a clean API for cookie manipulation without constant encrypt/decrypt calls
  • Ensure data privacy by making cookie contents unreadable to client-side inspection

The class maintains an internal array that gets encrypted/decrypted automatically when reading from or writing to the actual browser cookie.

SECURITY NOTES:

  • All cookie data is encrypted using AES-256-GCM via Primordyx\Crypto
  • Encryption key must be configured via Crypto::key() before use
  • httpOnly=true by default prevents JavaScript access (XSS protection)
  • secure=true by default requires HTTPS transmission
  • Cookie contents are completely opaque to client-side inspection
  • Consider cookie size limits: browsers typically allow ~4KB per cookie
Tags
example

Basic Usage:

 // Configure once
  Cookie::configure('my_app_session', 3600 * 24 * 7); // 7 days

  // Add data
  Cookie::add('user_id', 123);
  Cookie::add('preferences', ['theme' => 'dark', 'lang' => 'en']);

  // Send to browser
  Cookie::set();

  // Later, retrieve data
  $userId = Cookie::get('user_id');
  $prefs = Cookie::get('preferences', []);
example

Advanced Usage:

 // One-time cookie with custom settings
  Cookie::add('temp_token', $resetToken);
  Cookie::set('password_reset', 900, '/', '.example.com'); // 15 minutes

  // Shopping cart across subdomain
  Cookie::configure('shopping_cart', 3600 * 24 * 30, '/', '.store.com');
  Cookie::add('items', $cartItems);
  Cookie::set();
example

Development vs Production:

  if (Config::get('environment') === 'production') {
      Cookie::configure('app_prod', 3600 * 24 * 30, '/', '.mysite.com', true, true);
  } else {
      Cookie::configure('app_dev', 3600, '/', null, false, true);
  }
since
1.0.0

Table of Contents

Properties

$contents  : array<string|int, mixed>
Internal storage for cookie key-value pairs.
$defaultDomain  : string|null
Default cookie domain.
$defaultExpiration  : int
Default expiration time in seconds from now.
$defaultHttpOnly  : bool
Default HttpOnly flag (JavaScript access prevention).
$defaultName  : string|null
Default cookie name if none specified.
$defaultPath  : string
Default cookie path.
$defaultSecure  : bool
Default secure flag (HTTPS only).

Methods

add()  : void
Adds or updates a key-value pair in the internal cookie store.
all()  : array<string|int, mixed>
Alias for dump().
clear()  : void
Clears all stored key-value pairs from the internal store.
configure()  : void
Configure default cookie settings for all subsequent operations.
debug()  : void
Outputs the cookie contents as headers for debugging purposes.
domain()  : string|null
Sets or gets the default cookie domain.
drop()  : void
Removes a key from the internal cookie store.
dump()  : array<string|int, mixed>
Returns all key-value pairs currently stored in the internal array.
expiration()  : int
Sets or gets the default expiration time.
forget()  : void
Alias for drop(). Removes a key from the cookie store.
get()  : mixed
Gets the value for a given key, automatically setting it to default if not found.
has()  : bool
Alias for keyExists().
httpOnly()  : bool
Sets or gets the default HttpOnly flag.
init()  : void
Initializes the internal cookie store by decrypting the existing cookie, if present.
keyExists()  : bool
Checks if a key exists in the cookie store.
keyValue()  : mixed
Returns the value for a given key without auto-setting defaults.
name()  : string|null
Sets or gets the default cookie name.
path()  : string
Sets or gets the default cookie path.
secure()  : bool
Sets or gets the default secure flag.
sendToUser()  : void
Alias for set(). Sends the cookie to the user.
set()  : void
Writes the encrypted cookie to the user's browser.

Properties

$contents

Internal storage for cookie key-value pairs.

protected static array<string|int, mixed> $contents

Gets encrypted/decrypted when reading/writing to browser.

$defaultDomain

Default cookie domain.

protected static string|null $defaultDomain = null

$defaultExpiration

Default expiration time in seconds from now.

protected static int $defaultExpiration = 2592000

$defaultHttpOnly

Default HttpOnly flag (JavaScript access prevention).

protected static bool $defaultHttpOnly = true

$defaultName

Default cookie name if none specified.

protected static string|null $defaultName = null

$defaultPath

Default cookie path.

protected static string $defaultPath = '/'

$defaultSecure

Default secure flag (HTTPS only).

protected static bool $defaultSecure = true

Methods

add()

Adds or updates a key-value pair in the internal cookie store.

public static add(string $key, mixed $value) : void

The data is stored in memory until set() is called to encrypt and send the cookie to the browser. Any PHP data type can be stored.

Parameters
$key : string

The key to store the value under

$value : mixed

The value to store (any PHP data type)

Tags
example

Simple values:

  Cookie::add('user_id', 123);
  Cookie::add('username', 'john_doe');
  Cookie::add('is_admin', true);
example

Complex data:

  Cookie::add('user_preferences', [
      'theme' => 'dark',
      'language' => 'en',
      'notifications' => true
  ]);
  Cookie::add('shopping_cart', [
      ['id' => 1, 'qty' => 2, 'price' => 19.99],
      ['id' => 5, 'qty' => 1, 'price' => 34.50]
  ]);

all()

Alias for dump().

public static all() : array<string|int, mixed>

Provides a more semantic method name for getting all stored data.

Tags
see
dump()

For full documentation

Return values
array<string|int, mixed>

All stored key-value pairs

clear()

Clears all stored key-value pairs from the internal store.

public static clear() : void

This empties the internal array but doesn't affect the browser cookie until set() is called. When set() is called with an empty store, the browser cookie will be expired/removed.

Tags
example

Complete reset:

  Cookie::clear();
  Cookie::set(); // This will remove the cookie from browser

configure()

Configure default cookie settings for all subsequent operations.

public static configure(string $name[, int $expiration = 2592000 ][, string $path = '/' ][, string|null $domain = null ][, bool $secure = true ][, bool $httpOnly = true ]) : void

This is typically called once during application bootstrap to establish cookie defaults. Individual set() calls can still override these settings.

Parameters
$name : string

Default cookie name

$expiration : int = 2592000

Default expiration in seconds from now (default: 30 days)

$path : string = '/'

Default cookie path (default: '/')

$domain : string|null = null

Default cookie domain (default: null)

$secure : bool = true

Default secure flag - HTTPS only (default: true)

$httpOnly : bool = true

Default HttpOnly flag - prevent JavaScript access (default: true)

Tags
example

Application Bootstrap: // In your bootstrap.php or config setup: Cookie::configure( name: 'myapp_session', expiration: 3600 * 24 * 14, // 2 weeks path: '/', domain: '.example.com', // Share across subdomains secure: true, // HTTPS only httpOnly: true // Prevent JavaScript access );

example

Environment-Specific Configuration:

  if (Config::get('environment') === 'production') {
      Cookie::configure('app_prod', 3600 * 24 * 30, '/', '.mysite.com', true, true);
  } else {
      Cookie::configure('app_dev', 3600, '/', null, false, true);
  }

debug()

Outputs the cookie contents as headers for debugging purposes.

public static debug([string $suffix = '' ]) : void

Sends X-Primordyx-Cookie-* headers containing the cookie data. Useful for debugging cookie contents without exposing them in HTML.

Parameters
$suffix : string = ''

Optional suffix to include in header keys

Tags
example

Debug usage:

  Cookie::add('user_id', 123);
  Cookie::add('theme', 'dark');
  Cookie::debug('debug'); // Sends headers like:
  // X-Primordyx-Cookie-debuguser_id: 123
  // X-Primordyx-Cookie-debugtheme: "dark"

domain()

Sets or gets the default cookie domain.

public static domain([string|null $domain = null ]) : string|null

Use null for current domain only, or specify domain for subdomain sharing. Leading dot (e.g., '.example.com') allows all subdomains.

Parameters
$domain : string|null = null

If provided, sets the domain and returns the old domain.

Tags
example

Domain configurations:

  Cookie::domain(null);           // Current domain only
  Cookie::domain('example.com');  // example.com only
  Cookie::domain('.example.com'); // example.com and all subdomains
Return values
string|null

Returns the current/old domain.

drop()

Removes a key from the internal cookie store.

public static drop(string $key) : void

The key will be removed from memory immediately. Call set() to persist the change to the browser cookie.

Parameters
$key : string

The key to remove

Tags
example

Removing keys:

  Cookie::drop('temp_token');
  Cookie::drop('user_id');
  Cookie::set(); // Persist the removal

dump()

Returns all key-value pairs currently stored in the internal array.

public static dump() : array<string|int, mixed>

Useful for debugging, logging, or bulk operations on cookie data.

Tags
example

Getting all data:

  $allData = Cookie::dump();
  foreach ($allData as $key => $value) {
      echo "Cookie key: $key, value: " . json_encode($value) . "\n";
  }
Return values
array<string|int, mixed>

All stored key-value pairs

expiration()

Sets or gets the default expiration time.

public static expiration([int|null $seconds = null ]) : int

When called with no arguments, returns the current default expiration. When called with seconds, sets it as the new default and returns the old value.

Parameters
$seconds : int|null = null

If provided, sets expiration and returns the old value.

Tags
example

Common expiration times:

  Cookie::expiration(3600);           // 1 hour
  Cookie::expiration(3600 * 24);      // 1 day
  Cookie::expiration(3600 * 24 * 7);  // 1 week
  Cookie::expiration(3600 * 24 * 30); // 30 days
Return values
int

Returns the current/old expiration in seconds.

forget()

Alias for drop(). Removes a key from the cookie store.

public static forget(string $key) : void

Provides a more semantic method name for removing keys.

Parameters
$key : string

The key to remove

Tags
see
drop()

For full documentation

get()

Gets the value for a given key, automatically setting it to default if not found.

public static get(string $key[, mixed $default = null ]) : mixed

IMPORTANT: This method will ADD the default value to the cookie store if the key doesn't exist. Use has() + manual retrieval if you don't want this behavior.

Parameters
$key : string

The key to retrieve

$default : mixed = null

Value to set and return if key doesn't exist

Tags
example

Basic retrieval:

  $userId = Cookie::get('user_id'); // Returns null if not set
  $theme = Cookie::get('theme', 'light'); // Returns 'light' if not set
example

With complex defaults:

  $settings = Cookie::get('user_settings', [
      'notifications' => true,
      'theme' => 'dark',
      'language' => 'en'
  ]);
example

Avoiding auto-setting behavior:

  if (Cookie::has('optional_data')) {
      $data = Cookie::get('optional_data');
  }
  // OR use keyValue() which doesn't auto-set
see
has()

To check existence without setting defaults

see
keyValue()

Alias method that doesn't auto-set defaults

Return values
mixed

The stored value or the default

has()

Alias for keyExists().

public static has(string $key) : bool

Provides a shorter, more common method name for checking key existence.

Parameters
$key : string

The key to check

Tags
see
keyExists()

For full documentation

Return values
bool

True if key exists, false otherwise

httpOnly()

Sets or gets the default HttpOnly flag.

public static httpOnly([bool|null $httpOnly = null ]) : bool

When true, prevents JavaScript access to the cookie (XSS protection). Should almost always be true unless you specifically need JS access.

Parameters
$httpOnly : bool|null = null

If provided, sets the HttpOnly flag and returns the old value.

Tags
example

HttpOnly configurations:

  Cookie::httpOnly(true);  // Prevent JavaScript access (recommended)
  Cookie::httpOnly(false); // Allow JavaScript access (rarely needed)
Return values
bool

Returns the current/old HttpOnly flag.

init()

Initializes the internal cookie store by decrypting the existing cookie, if present.

public static init([string|null $cookieName = null ]) : void

This method is called automatically by other methods, but can be called manually for explicit initialization. It will only initialize once per request. If a cookie exists, it will be decrypted and loaded into the internal store.

Parameters
$cookieName : string|null = null

Optional cookie name override

Tags
throws
RuntimeException

If no cookie name configured

throws
RuntimeException

If decryption fails (malformed cookie data)

see
Crypto::decrypt()

For decryption implementation

keyExists()

Checks if a key exists in the cookie store.

public static keyExists(string $key) : bool

Returns true if the key exists, regardless of its value (even if null). Use this to check existence without accidentally setting defaults.

Parameters
$key : string

The key to check

Tags
example

Checking existence:

  if (Cookie::keyExists('user_id')) {
      $userId = Cookie::get('user_id');
  }

  // Check before conditionally adding
  if (!Cookie::keyExists('visit_count')) {
      Cookie::add('visit_count', 1);
  } else {
      Cookie::add('visit_count', Cookie::get('visit_count') + 1);
  }
Return values
bool

True if key exists, false otherwise

keyValue()

Returns the value for a given key without auto-setting defaults.

public static keyValue(string $key[, mixed $default = null ]) : mixed

Unlike get(), this method will NOT add the default value to the store if the key doesn't exist. It simply returns the default.

Parameters
$key : string

The key to retrieve

$default : mixed = null

Value to return if key doesn't exist

Tags
example

Safe retrieval:

  $userId = Cookie::keyValue('user_id'); // Returns null, doesn't set anything
  $theme = Cookie::keyValue('theme', 'light'); // Returns 'light', doesn't set anything
see
get()

For auto-setting behavior

Return values
mixed

The stored value or the default

name()

Sets or gets the default cookie name.

public static name([string|null $name = null ]) : string|null

When called with no arguments, returns the current default name. When called with a name, sets it as the new default and returns the old name.

Parameters
$name : string|null = null

If provided, sets the name and returns the old name.

Tags
example

Getting current name:

  $currentName = Cookie::name(); // Returns current default
example

Setting new name:

  $oldName = Cookie::name('new_cookie_name'); // Sets and returns old name
Return values
string|null

Returns the current/old name.

path()

Sets or gets the default cookie path.

public static path([string|null $path = null ]) : string

The path determines which URLs the cookie will be sent to. Use '/' for site-wide cookies, '/admin' for admin-only cookies, etc.

Parameters
$path : string|null = null

If provided, sets the path and returns the old path.

Tags
example

Path restrictions:

  Cookie::path('/');        // Available site-wide
  Cookie::path('/admin');   // Only available under /admin/
  Cookie::path('/api/v1');  // Only available under /api/v1/
Return values
string

Returns the current/old path.

secure()

Sets or gets the default secure flag.

public static secure([bool|null $secure = null ]) : bool

When true, cookie will only be transmitted over HTTPS connections. Should be true in production for security.

Parameters
$secure : bool|null = null

If provided, sets the secure flag and returns the old value.

Tags
example

Security configurations:

  Cookie::secure(true);  // HTTPS only (recommended for production)
  Cookie::secure(false); // HTTP and HTTPS (development only)
Return values
bool

Returns the current/old secure flag.

sendToUser()

Alias for set(). Sends the cookie to the user.

public static sendToUser([string|null $cookieName = null ][, int|null $expiration = null ][, string|null $path = null ][, string|null $domain = null ][, bool|null $secure = null ][, bool|null $httpOnly = null ]) : void

Provides a more descriptive method name for when you want to be explicit about sending the cookie to the user's browser.

Parameters
$cookieName : string|null = null

Optional cookie name override

$expiration : int|null = null

Optional expiration override (seconds from now)

$path : string|null = null

Optional path override

$domain : string|null = null

Optional domain override

$secure : bool|null = null

Optional secure flag override

$httpOnly : bool|null = null

Optional HttpOnly flag override

Tags
throws
RuntimeException

If no cookie name configured

throws
RuntimeException

If encryption fails

throws
RuntimeException

If headers already sent

throws
RandomException

If encryption fails (cryptographically secure random bytes unavailable)

see
set()

For full documentation

set()

Writes the encrypted cookie to the user's browser.

public static set([string|null $cookieName = null ][, int|null $expiration = null ][, string|null $path = null ][, string|null $domain = null ][, bool|null $secure = null ][, bool|null $httpOnly = null ]) : void

Encrypts the internal key-value store and sends it as a single cookie. If the internal store is empty, the cookie will be expired (removed). Headers must not have been sent yet for this to work.

Parameters
$cookieName : string|null = null

Optional cookie name override

$expiration : int|null = null

Optional expiration override (seconds from now)

$path : string|null = null

Optional path override

$domain : string|null = null

Optional domain override

$secure : bool|null = null

Optional secure flag override

$httpOnly : bool|null = null

Optional HttpOnly flag override

Tags
throws
RuntimeException

If no cookie name configured

throws
RuntimeException

If encryption fails

throws
RuntimeException

If headers already sent

throws
RandomException

If encryption fails (cryptographically secure random bytes unavailable)

example

Basic usage:

  Cookie::add('user_id', 123);
  Cookie::set(); // Uses configured defaults
example

Custom expiration:

  Cookie::set('remember_me', 3600 * 24 * 30); // 30 days
example

Full customization:

  Cookie::set(
      cookieName: 'temp_session',
      expiration: 900,              // 15 minutes
      path: '/admin',
      domain: '.secure.example.com',
      secure: true,
      httpOnly: true
  );
see
Crypto::encrypt()

For encryption implementation


        
On this page

Search results