Cookies

An HTTP cookie (web cookie, browser cookie) is a small piece of data that a server sends to the user’s web browser. The browser may store it and send it back with later requests to the same server. Typically, it’s used to tell if two requests came from the same browser - keeping a user logged-in, for example. It remembers stateful information for the stateless HTTP protocol.

Cookies are mainly used for three purposes:

  • Session management: Logins, shopping carts, game scores, or anything else the server should remember

  • Personalization: User preferences, themes, and other settings

  • Tracking: Recording and analyzing user behavior

To help you efficiently send cookies to browsers, CodeIgniter provides the CodeIgniter\Cookie\Cookie class to abstract the cookie interaction.

Creating Cookies

There are currently four (4) ways to create a new Cookie value object.

<?php

use CodeIgniter\Cookie\Cookie;
use DateTime;

// Using the constructor
$cookie = new Cookie(
    'remember_token',
    'f699c7fd18a8e082d0228932f3acd40e1ef5ef92efcedda32842a211d62f0aa6',
    [
        'expires'  => new DateTime('+2 hours'),
        'prefix'   => '__Secure-',
        'path'     => '/',
        'domain'   => '',
        'secure'   => true,
        'httponly' => true,
        'raw'      => false,
        'samesite' => Cookie::SAMESITE_LAX,
    ]
);

// Supplying a Set-Cookie header string
$cookie = Cookie::fromHeaderString(
    'remember_token=f699c7fd18a8e082d0228932f3acd40e1ef5ef92efcedda32842a211d62f0aa6; Path=/; Secure; HttpOnly; SameSite=Lax',
    false, // raw
);

// Using the fluent builder interface
$cookie = (new Cookie('remember_token'))
    ->withValue('f699c7fd18a8e082d0228932f3acd40e1ef5ef92efcedda32842a211d62f0aa6')
    ->withPrefix('__Secure-')
    ->withExpires(new DateTime('+2 hours'))
    ->withPath('/')
    ->withDomain('')
    ->withSecure(true)
    ->withHTTPOnly(true)
    ->withSameSite(Cookie::SAMESITE_LAX);

// Using the global function `cookie` which implicitly calls `new Cookie()`
$cookie = cookie('remember_token', 'f699c7fd18a8e082d0228932f3acd40e1ef5ef92efcedda32842a211d62f0aa6');

When constructing the Cookie object, only the name attribute is required. All other else are optional. If the optional attributes are not modified, their values will be filled up by the default values saved in the Cookie class.

Overriding Defaults

To override the defaults currently stored in the class, you can pass a Config\Cookie instance or an array of defaults to the static Cookie::setDefaults() method.

<?php

use CodeIgniter\Cookie\Cookie;
use Config\Cookie as CookieConfig;

// pass in a Config\Cookie instance before constructing a Cookie class
Cookie::setDefaults(new CookieConfig());
$cookie = new Cookie('login_token');

// pass in an array of defaults
$myDefaults = [
    'expires'  => 0,
    'samesite' => Cookie::SAMESITE_STRICT,
];
Cookie::setDefaults($myDefaults);
$cookie = new Cookie('login_token');

Passing the Config\Cookie instance or an array to Cookie::setDefaults() will effectively overwrite your defaults and will persist until new defaults are passed.

Changing Defaults for a Limited Time

If you do not want this behavior but only want to change defaults for a limited time, you can take advantage of Cookie::setDefaults() return which returns the old defaults array.

<?php

use CodeIgniter\Cookie\Cookie;
use Config\Cookie as CookieConfig;

$oldDefaults = Cookie::setDefaults(new CookieConfig());
$cookie      = new Cookie('my_token', 'muffins');

// return the old defaults
Cookie::setDefaults($oldDefaults);

Immutable Cookies

A new Cookie instance is an immutable value object representation of an HTTP cookie. Being immutable, modifying any of the instance’s attributes will not affect the original instance. The modification always returns a new instance. You need to retain this new instance in order to use it.

<?php

use CodeIgniter\Cookie\Cookie;

$cookie = new Cookie('login_token', 'admin');
$cookie->getName(); // 'login_token'

$cookie->withName('remember_token');
$cookie->getName(); // 'login_token'

$new = $cookie->withName('remember_token');
$new->getName(); // 'remember_token'

Sending Cookies

Set the Cookie objects in the CookieStore of the Response object, and the framework will automatically send the cookies.

Use CodeIgniter\HTTP\Response::setCookie() to set:

<?php

use CodeIgniter\Cookie\Cookie;
use Config\Services;

$response = Services::response();

$cookie = new Cookie(
    'remember_token',
    'f699c7fd18a8e082d0228932f3acd40e1ef5ef92efcedda32842a211d62f0aa6',
    [
        'max-age' => 3600 * 2, // Expires in 2 hours
    ]
);

$response->setCookie($cookie);

You can also use the set_cookie() helper function:

<?php

use CodeIgniter\Cookie\Cookie;

helper('cookie');

$cookie = new Cookie(
    'remember_token',
    'f699c7fd18a8e082d0228932f3acd40e1ef5ef92efcedda32842a211d62f0aa6',
    [
        'max-age' => 3600 * 2, // Expires in 2 hours
    ]
);

set_cookie($cookie);

Class Reference

class CodeIgniter\Cookie\Cookie
static setDefaults([$config = []])
Parameters
  • $config (\Config\Cookie|array) – The configuration array or instance

Return type

array

Returns

The old defaults

Set the default attributes to a Cookie instance by injecting the values from the Config\Cookie config or an array.

static fromHeaderString(string $header[, bool $raw = false])
Parameters
  • $header (string) – The Set-Cookie header string

  • $raw (bool) – Whether this cookie is not to be URL encoded and sent via setrawcookie()

Return type

Cookie

Returns

Cookie instance

Throws

CookieException

Create a new Cookie instance from a Set-Cookie header.

__construct(string $name[, string $value = ''[, array $options = []]])
Parameters
  • $name (string) – The cookie name

  • $value (string) – The cookie value

  • $options (array) – The cookie options

Return type

Cookie

Returns

Cookie instance

Throws

CookieException

Construct a new Cookie instance.

getId()
Return type

string

Returns

The ID used in indexing in the cookie collection.

getPrefix() string
getName() string
getPrefixedName() string
getValue() string
getExpiresTimestamp() int
getExpiresString() string
isExpired() bool
getMaxAge() int
getDomain() string
getPath() string
isSecure() bool
isHTTPOnly() bool
getSameSite() string
isRaw() bool
getOptions() array
withRaw([bool $raw = true])
Parameters
  • $raw (bool) –

Return type

Cookie

Returns

new Cookie instance

Creates a new Cookie with URL encoding option updated.

withPrefix([string $prefix = ''])
Parameters
  • $prefix (string) –

Return type

Cookie

Returns

new Cookie instance

Creates a new Cookie with new prefix.

withName(string $name)
Parameters
  • $name (string) –

Return type

Cookie

Returns

new Cookie instance

Creates a new Cookie with new name.

withValue(string $value)
Parameters
  • $value (string) –

Return type

Cookie

Returns

new Cookie instance

Creates a new Cookie with new value.

withExpires($expires)
Parameters
  • $expires (DateTimeInterface|string|int) –

Return type

Cookie

Returns

new Cookie instance

Creates a new Cookie with new cookie expires time.

withExpired()
Return type

Cookie

Returns

new Cookie instance

Creates a new Cookie that will expire from the browser.

withNeverExpiring()

Deprecated since version 4.2.6.

Important

This method is deprecated. It will be removed in future releases.

Parameters
  • $name (string) –

Return type

Cookie

Returns

new Cookie instance

Creates a new Cookie that will virtually never expire.

withDomain(?string $domain)
Parameters
  • $domain (string|null) –

Return type

Cookie

Returns

new Cookie instance

Creates a new Cookie with new domain.

withPath(?string $path)
Parameters
  • $path (string|null) –

Return type

Cookie

Returns

new Cookie instance

Creates a new Cookie with new path.

withSecure([bool $secure = true])
Parameters
  • $secure (bool) –

Return type

Cookie

Returns

new Cookie instance

Creates a new Cookie with new “Secure” attribute.

withHTTPOnly([bool $httponly = true])
Parameters
  • $httponly (bool) –

Return type

Cookie

Returns

new Cookie instance

Creates a new Cookie with new “HttpOnly” attribute.

withSameSite(string $samesite)
Parameters
  • $samesite (string) –

Return type

Cookie

Returns

new Cookie instance

Creates a new Cookie with new “SameSite” attribute.

toHeaderString()
Return type

string

Returns

Returns the string representation that can be passed as a header string.

toArray()
Return type

array

Returns

Returns the array representation of the Cookie instance.

class CodeIgniter\Cookie\CookieStore
static fromCookieHeaders(array $headers[, bool $raw = false])
Parameters
  • $header (array) – Array of Set-Cookie headers

  • $raw (bool) – Whether not to use URL encoding

Return type

CookieStore

Returns

CookieStore instance

Throws

CookieException

Creates a CookieStore from an array of Set-Cookie headers.

__construct(array $cookies)
Parameters
  • $cookies (array) – Array of Cookie objects

Return type

CookieStore

Returns

CookieStore instance

Throws

CookieException

has(string $name[, string $prefix = ''[, ?string $value = null]]) bool
Parameters
  • $name (string) – Cookie name

  • $prefix (string) – Cookie prefix

  • $value (string|null) – Cookie value

Return type

bool

Returns

Checks if a Cookie object identified by name and prefix is present in the collection.

get(string $name[, string $prefix = '']) Cookie
Parameters
  • $name (string) – Cookie name

  • $prefix (string) – Cookie prefix

Return type

Cookie

Returns

Retrieves an instance of Cookie identified by a name and prefix.

Throws

CookieException

put(Cookie $cookie) CookieStore
Parameters
  • $cookie (Cookie) – A Cookie object

Return type

CookieStore

Returns

new CookieStore instance

Store a new cookie and return a new collection. The original collection is left unchanged.

remove(string $name[, string $prefix = '']) CookieStore
Parameters
  • $name (string) – Cookie name

  • $prefix (string) – Cookie prefix

Return type

CookieStore

Returns

new CookieStore instance

Removes a cookie from a collection and returns an updated collection. The original collection is left unchanged.

dispatch() void
Return type

void

Dispatches all cookies in store.

display() array
Return type

array

Returns

Returns all cookie instances in store.

clear() void
Return type

void

Clears the cookie collection.