popphp / pop-cookie
Pop Cookie Component for Pop PHP Framework
Requires
- php: >=8.4.0
Requires (Dev)
- phpstan/phpstan: ^2.2
- phpunit/phpunit: ^12.5.0
README
- Overview
- Install
- Quickstart
- Storing Non-Scalar Values
- Deleting Cookies
- Inspecting Cookie Configuration
- Error Handling
Overview
pop-cookie is a component used to securely create and manage cookies in a PHP web environment.
With it, you can set and retrieve cookie values, as well as set required configuration options
for the web application environment.
pop-cookie is a component of the Pop PHP Framework.
Install
Install pop-cookie using Composer.
composer require popphp/pop-cookie
Or, require it in your composer.json file
"require": {
"popphp/pop-cookie" : "^5.0.0"
}
Quickstart
The cookie object is a singleton, obtained via getInstance(), which takes an options array. Calling
getInstance() again later with a new options array reconfigures the same shared instance rather than
creating a new one or being ignored:
use Pop\Cookie\Cookie; $cookie = Cookie::getInstance([ 'expires' => time() + 3600, 'path' => '/', 'domain' => 'www.domain.com', 'secure' => true, 'httponly' => true, 'samesite' => 'Lax', ]); // Later, in the same request, reconfigure the same instance: $cookie = Cookie::getInstance(['expires' => time() + 7200]);
Available options
$options = [ 'expires' => time() + 3600, 'path' => '/', 'domain' => 'www.domain.com', 'secure' => true, 'httponly' => true, 'samesite' => 'Lax' // 'Lax', 'Strict', 'None' ];
samesite => 'None'requiressecureto be (or become, in the same call)true. Browsers rejectSameSite=Nonecookies that aren't alsoSecure, soCookiethrows aPop\Cookie\Exceptionrather than silently producing a cookie that would be dropped client-side. See Error Handling.
Setting cookie values
// Set cookie values $cookie->foo = 'bar'; $cookie['baz'] = 123; // Or, with a per-call options override $cookie->set('foo', 'bar', ['expires' => time() + 3600]);
Setting a value calls PHP's native
setcookie()immediately, which only sends theSet-Cookieheader for the next request — it does not update the current request's$_COOKIEsuperglobal. Reading$cookie->fooback in the same request that set it will not reflect the new value until the following request.
Accessing cookie values
echo $cookie->foo; echo $cookie['baz']; // Check whether a cookie is set if (isset($cookie->foo)) { /* ... */ } if (isset($cookie['baz'])) { /* ... */ }
Unsetting cookie values
unset($cookie->foo); unset($cookie['baz']);
Iterating over cookies
Cookie implements Countable and IteratorAggregate over the current $_COOKIE data:
echo count($cookie); // number of cookies currently set foreach ($cookie as $name => $value) { echo $name . ': ' . $value; } $all = $cookie->toArray(); // raw $_COOKIE as an array
Storing Non-Scalar Values
Any value that isn't already a string or numeric is transparently JSON-encoded on write and decoded back on
read, so arrays, bool, and null round-trip automatically:
$cookie->preferences = ['theme' => 'dark', 'perPage' => 25]; $cookie->rememberMe = true; // On a later request: $cookie->preferences; // ['theme' => 'dark', 'perPage' => 25] $cookie->rememberMe; // true
Numeric values (int/float) are stored as-is and read back in their raw string form, same as any other
cookie value — $_COOKIE (and therefore this library) only ever deals in strings once a value round-trips
through the browser.
Deleting Cookies
Delete a single cookie with delete(), or every cookie currently set with clear(). Both accept an optional
$options array, applied the same way as getInstance()/set():
$cookie->delete('foo'); $cookie->delete('foo', ['path' => '/', 'domain' => 'www.domain.com']); $cookie->clear(); // deletes every cookie currently in $_COOKIE
unset($cookie->foo) / unset($cookie['foo']) are equivalent to delete() for a single cookie, without the
$options override.
Inspecting Cookie Configuration
$cookie->getOptions(); // array shaped for PHP's setcookie() options parameter $cookie->getExpires(); // int $cookie->getPath(); // string $cookie->getDomain(); // string|null $cookie->isSecure(); // bool $cookie->isHttpOnly(); // bool $cookie->getSamesite(); // string $cookie->getIp(); // string|null - the requesting client's IP address
Error Handling
Cookie throws Pop\Cookie\Exception rather than failing silently in these cases:
setOptions()— and thereforegetInstance(),set(),delete(), andclear(), which all accept and apply an$optionsarray — throws ifsamesiteis set to anything other than'None','Lax', or'Strict'.setOptions()throws if the resulting configuration hassamesite => 'None'withsecurenottrue.set(),delete(),clear(), andunset($cookie->foo)all throw if the underlying call to PHP'ssetcookie()fails (for example, if output has already been sent and headers can no longer be modified).
use Pop\Cookie\Cookie; use Pop\Cookie\Exception; try { $cookie->setOptions(['samesite' => 'None', 'secure' => false]); } catch (Exception $e) { // 'samesite' => 'None' requires 'secure' => true }