PHPackages                             josantonius/cookie - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. josantonius/cookie

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

josantonius/cookie
==================

PHP library for handling cookies.

v2.0.7(1y ago)2238.7k↓31.3%124MITPHPPHP ^8.1

Since Dec 15Pushed 1y ago1 watchersCompare

[ Source](https://github.com/josantonius/php-cookie)[ Packagist](https://packagist.org/packages/josantonius/cookie)[ GitHub Sponsors](https://github.com/Josantonius)[ RSS](/packages/josantonius-cookie/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (10)Dependencies (4)Versions (18)Used By (4)

PHP Cookie library
==================

[](#php-cookie-library)

[![Latest Stable Version](https://camo.githubusercontent.com/04156c292b746ad302b5e2d8b2b25523ea85d859272c7d132a68f00c69e96d48/68747470733a2f2f706f7365722e707567782e6f72672f6a6f73616e746f6e6975732f636f6f6b69652f762f737461626c65)](https://packagist.org/packages/josantonius/cookie)[![License](https://camo.githubusercontent.com/1becf3efdc0d2f9cc41e089bdc133eafef99d7e6cbd6e646973ba4ba04d29a73/68747470733a2f2f706f7365722e707567782e6f72672f6a6f73616e746f6e6975732f636f6f6b69652f6c6963656e7365)](LICENSE)[![Total Downloads](https://camo.githubusercontent.com/92aad34480bb3261ede1594dbfb75c6acacb7fd8439eb6d89dc734da7f42bcfe/68747470733a2f2f706f7365722e707567782e6f72672f6a6f73616e746f6e6975732f636f6f6b69652f646f776e6c6f616473)](https://packagist.org/packages/josantonius/cookie)[![CI](https://github.com/josantonius/php-cookie/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/josantonius/php-cookie/actions/workflows/ci.yml)[![CodeCov](https://camo.githubusercontent.com/548c96c90385607bc362abaddc1194582b8461e8ea2e692c5e0efbf34c7909d3/68747470733a2f2f636f6465636f762e696f2f67682f6a6f73616e746f6e6975732f7068702d636f6f6b69652f6272616e63682f6d61696e2f67726170682f62616467652e737667)](https://codecov.io/gh/josantonius/php-cookie)[![PSR1](https://camo.githubusercontent.com/b502a899c9aec217e98971160f816f87346be272cf1a25cfa4793f2ee724bfc8/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5053522d312d6635373034362e737667)](https://www.php-fig.org/psr/psr-1/)[![PSR4](https://camo.githubusercontent.com/d1c090de87e968254a6658528f3bfe9c9dad422d6047fd1323dc211560182c01/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5053522d342d3962353962362e737667)](https://www.php-fig.org/psr/psr-4/)[![PSR12](https://camo.githubusercontent.com/19c529c6dc0656dcc2a16c1a84af450b7bd0dc7b0571b8f17e4fc9f2414f8821/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5053522d31322d3161626339632e737667)](https://www.php-fig.org/psr/psr-12/)

**Translations**: [Español](.github/lang/es-ES/README.md)

PHP library for handling cookies.

---

- [Requirements](#requirements)
- [Installation](#installation)
- [Available Classes](#available-classes)
    - [Cookie Class](#cookie-class)
    - [Cookie Facade](#cookie-facade)
- [Exceptions Used](#exceptions-used)
- [Usage](#usage)
- [About Cookie Expires](#about-cookie-expires)
- [Tests](#tests)
- [TODO](#todo)
- [Changelog](#changelog)
- [Contribution](#contribution)
- [Sponsor](#sponsor)
- [License](#license)

---

Requirements
------------

[](#requirements)

- Operating System: Linux.
- PHP versions: 8.1 | 8.2 | 8.3.

Installation
------------

[](#installation)

The preferred way to install this extension is through [Composer](http://getcomposer.org/download/).

To install **PHP Cookie library**, simply:

```
composer require josantonius/cookie
```

The previous command will only install the necessary files, if you prefer to **download the entire source code** you can use:

```
composer require josantonius/cookie --prefer-source
```

You can also **clone the complete repository** with Git:

```
git clone https://github.com/josantonius/php-cookie.git
```

Available Classes
-----------------

[](#available-classes)

### Cookie Class

[](#cookie-class)

`Josantonius\Cookie\Cookie`

Sets cookie options:

```
/**
 * Cookie options:
 *
 * domain:   Domain for which the cookie is available.
 * expires:  The time the cookie will expire.
 * httpOnly: If cookie will only be available through the HTTP protocol.
 * path:     Path for which the cookie is available.
 * raw:      If cookie will be sent as a raw string.
 * sameSite: Enforces the use of a Lax or Strict SameSite policy.
 * secure:   If cookie will only be available through the HTTPS protocol.
 *
 * These settings will be used to create and delete cookies.
 *
 * @throws CookieException if $sameSite value is wrong.
 *
 * @see https://www.php.net/manual/en/datetime.formats.php for date formats.
 * @see https://www.php.net/manual/en/function.setcookie.php for more information.
 */
public function __construct(
    private string              $domain   = '',
    private int|string|DateTime $expires  = 0,
    private bool                $httpOnly = false,
    private string              $path     = '/',
    private bool                $raw      = false,
    private null|string         $sameSite = null,
    private bool                $secure   = false
);
```

Sets a cookie by name:

```
/**
 * @throws CookieException if headers already sent.
 * @throws CookieException if failure in date/time string analysis.
 */
public function set(
    string $name,
    mixed $value,
    null|int|string|DateTime $expires = null
): void;
```

Sets several cookies at once:

```
/**
 * If cookies exist they are replaced, if they do not exist they are created.
 *
 * @throws CookieException if headers already sent.
 */
public function replace(
    array $data,
    null|int|string|DateTime $expires = null
): void;
```

Gets a cookie by name:

```
/**
 * Optionally defines a default value when the cookie does not exist.
 */
public function get(string $name, mixed $default = null): mixed;
```

Gets all cookies:

```
public function all(): array;
```

Check if a cookie exists:

```
public function has(string $name): bool;
```

Deletes a cookie by name and returns its value:

```
/**
 * Optionally defines a default value when the cookie does not exist.
 *
 * @throws CookieException if headers already sent.
 */
public function pull(string $name, mixed $default = null): mixed;
```

Deletes an cookie by name:

```
/**
 * @throws CookieException if headers already sent.
 * @throws CookieException if failure in date/time string analysis.
 */
public function remove(string $name): void;
```

### Cookie Facade

[](#cookie-facade)

`Josantonius\Cookie\Facades\Cookie`

Sets cookie options:

```
/**
 * Cookie options:
 *
 * domain:   Domain for which the cookie is available.
 * expires:  The time the cookie will expire.
 * httpOnly: If cookie will only be available through the HTTP protocol.
 * path:     Path for which the cookie is available.
 * raw:      If cookie will be sent as a raw string.
 * sameSite: Enforces the use of a Lax or Strict SameSite policy.
 * secure:   If cookie will only be available through the HTTPS protocol.
 *
 * These settings will be used to create and delete cookies.
 *
 * @throws CookieException if $sameSite value is wrong.
 *
 * @see https://www.php.net/manual/en/datetime.formats.php for date formats.
 * @see https://www.php.net/manual/en/function.setcookie.php for more information.
 */
public static function options(
    string              $domain   = '',
    int|string|DateTime $expires  = 0,
    bool                $httpOnly = false,
    string              $path     = '/',
    bool                $raw      = false,
    null|string         $sameSite = null,
    bool                $secure   = false
): void;
```

Sets a cookie by name:

```
/**
 * @throws CookieException if headers already sent.
 * @throws CookieException if failure in date/time string analysis.
 */
public static function set(
    string $name,
    mixed $value,
    null|int|string|DateTime $expires = null
): void;
```

Sets several cookies at once:

```
/**
 * If cookies exist they are replaced, if they do not exist they are created.
 *
 * @throws CookieException if headers already sent.
 */
public static function replace(
    array $data,
    null|int|string|DateTime $expires = null
): void;
```

Gets a cookie by name:

```
/**
 * Optionally defines a default value when the cookie does not exist.
 */
public static function get(string $name, mixed $default = null): mixed;
```

Gets all cookies:

```
public static function all(): array;
```

Check if a cookie exists:

```
public static function has(string $name): bool;
```

Deletes a cookie by name and returns its value:

```
/**
 * Optionally defines a default value when the cookie does not exist.
 *
 * @throws CookieException if headers already sent.
 */
public static function pull(string $name, mixed $default = null): mixed;
```

Deletes an cookie by name:

```
/**
 * @throws CookieException if headers already sent.
 * @throws CookieException if failure in date/time string analysis.
 */
public static function remove(string $name): void;
```

Exceptions Used
---------------

[](#exceptions-used)

```
use Josantonius\Cookie\Exceptions\CookieException;
```

Usage
-----

[](#usage)

Example of use for this library:

### Create Cookie instance with default options

[](#create-cookie-instance-with-default-options)

```
use Josantonius\Cookie\Cookie;

$cookie = new Cookie();
```

```
use Josantonius\Cookie\Facades\Cookie;

Cookie::options();
```

### Create Cookie instance with custom options

[](#create-cookie-instance-with-custom-options)

```
use Josantonius\Cookie\Cookie;

$cookie = new Cookie(
    domain: 'example.com',
    expires: time() + 3600,
    httpOnly: true,
    path: '/foo',
    raw: true,
    sameSite: 'Strict',
    secure: true,
);
```

```
use Josantonius\Cookie\Facades\Cookie;

Cookie::options(
    expires: 'now +1 hour',
    httpOnly: true,
);
```

### Sets a cookie by name

[](#sets-a-cookie-by-name)

```
use Josantonius\Cookie\Cookie;

$cookie = new Cookie();

$cookie->set('foo', 'bar');
```

```
use Josantonius\Cookie\Facades\Cookie;

Cookie::set('foo', 'bar');
```

### Sets a cookie by name modifying the expiration time

[](#sets-a-cookie-by-name-modifying-the-expiration-time)

```
use Josantonius\Cookie\Cookie;

$cookie = new Cookie();

$cookie->set('foo', 'bar', time() + 3600);
```

```
use Josantonius\Cookie\Facades\Cookie;

Cookie::set('foo', 'bar', new DateTime('now +1 hour'));
```

### Sets several cookies at once

[](#sets-several-cookies-at-once)

```
use Josantonius\Cookie\Cookie;

$cookie = new Cookie();

$cookie->replace([
    'foo' => 'bar',
    'bar' => 'foo'
]);
```

```
use Josantonius\Cookie\Facades\Cookie;

Cookie::replace([
    'foo' => 'bar',
    'bar' => 'foo'
], time() + 3600);
```

### Sets several cookies at once modifying the expiration time

[](#sets-several-cookies-at-once-modifying-the-expiration-time)

```
use Josantonius\Cookie\Cookie;

$cookie = new Cookie();

$cookie->replace([
    'foo' => 'bar',
    'bar' => 'foo'
], time() + 3600);
```

```
use Josantonius\Cookie\Facades\Cookie;

Cookie::replace([
    'foo' => 'bar',
    'bar' => 'foo'
], time() + 3600);
```

### Gets a cookie by name

[](#gets-a-cookie-by-name)

```
use Josantonius\Cookie\Cookie;

$cookie = new Cookie();

$cookie->get('foo'); // null if the cookie does not exist
```

```
use Josantonius\Cookie\Facades\Cookie;

Cookie::get('foo'); // null if the cookie does not exist
```

### Gets a cookie by name with default value if cookie does not exist

[](#gets-a-cookie-by-name-with-default-value-if-cookie-does-not-exist)

```
use Josantonius\Cookie\Cookie;

$cookie = new Cookie();

$cookie->get('foo', false); // false if cookie does not exist
```

```
use Josantonius\Cookie\Facades\Cookie;

Cookie::get('foo', false); // false if cookie does not exist
```

### Gets all cookies

[](#gets-all-cookies)

```
use Josantonius\Cookie\Cookie;

$cookie = new Cookie();

$cookie->all();
```

```
use Josantonius\Cookie\Facades\Cookie;

Cookie::all();
```

### Check if a cookie exists

[](#check-if-a-cookie-exists)

```
use Josantonius\Cookie\Cookie;

$cookie = new Cookie();

$cookie->has('foo');
```

```
use Josantonius\Cookie\Facades\Cookie;

Cookie::has('foo');
```

### Deletes a cookie by name and returns its value

[](#deletes-a-cookie-by-name-and-returns-its-value)

```
use Josantonius\Cookie\Cookie;

$cookie = new Cookie();

$cookie->pull('foo'); // null if attribute does not exist
```

```
use Josantonius\Cookie\Facades\Cookie;

Cookie::pull('foo'); // null if attribute does not exist
```

### Deletes a cookie and returns its value or default value if does not exist

[](#deletes-a-cookie-and-returns-its-value-or-default-value-if-does-not-exist)

```
use Josantonius\Cookie\Cookie;

$cookie = new Cookie();

$cookie->pull('foo', false); // false if attribute does not exist
```

```
use Josantonius\Cookie\Facades\Cookie;

Cookie::pull('foo', false); // false if attribute does not exist
```

### Deletes an cookie by name

[](#deletes-an-cookie-by-name)

```
use Josantonius\Cookie\Cookie;

$cookie = new Cookie();

$cookie->remove('foo');
```

```
use Josantonius\Cookie\Facades\Cookie;

Cookie::remove('foo');
```

About cookie expires
--------------------

[](#about-cookie-expires)

- The **expires** parameter used in several methods of this library accepts the following types: `int|string|DateTime`.

    - `Integers` will be handled as unix time except zero.
    - `Strings` will be handled as date/time formats. See supported [Date and Time Formats](https://www.php.net/manual/en/datetime.formats.php)for more information.

        ```
        $cookie = new Cookie(
            expires: '2016-12-15 +1 day'
        );
        ```

        It would be similar to:

        ```
        $cookie = new Cookie(
            expires: new DateTime('2016-12-15 +1 day')
        );
        ```
    - `DateTime` objects will be used to obtain the unix time.
- If the **expires** parameter is used in the `set` or `replace` methods, it will be taken instead of the **expires** value set in the cookie options.

    ```
    $cookie = new Cookie(
        expires: 'now +1 minute'
    );

    $cookie->set('foo', 'bar');                        // Expires in 1 minute

    $cookie->set('bar', 'foo', 'now +8 days');         // Expires in 8 days

    $cookie->replace(['foo' => 'bar']);                // Expires in 1 minute

    $cookie->replace(['foo' => 'bar'], time() + 3600); // Expires in 1 hour
    ```
- If the **expires** parameter passed in the options is a date/time string, it is formatted when using the `set` or `replace` method and not when setting the options.

    ```
    $cookie = new Cookie(
        expires: 'now +1 minute', // It will not be formatted as unix time yet
    );

    $cookie->set('foo', 'bar');   // It is will formatted now and expires in 1 minute
    ```

Tests
-----

[](#tests)

To run [tests](tests) you just need [composer](http://getcomposer.org/download/)and to execute the following:

```
git clone https://github.com/josantonius/php-cookie.git
```

```
cd php-cookie
```

```
composer install
```

Run unit tests with [PHPUnit](https://phpunit.de/):

```
composer phpunit
```

Run code standard tests with [PHPCS](https://github.com/squizlabs/PHP_CodeSniffer):

```
composer phpcs
```

Run [PHP Mess Detector](https://phpmd.org/) tests to detect inconsistencies in code style:

```
composer phpmd
```

Run all previous tests:

```
composer tests
```

TODO
----

[](#todo)

- Add new feature
- Improve tests
- Improve documentation
- Improve English translation in the README file
- Refactor code for disabled code style rules (see phpmd.xml and phpcs.xml)

Changelog
---------

[](#changelog)

Detailed changes for each release are documented in the [release notes](https://github.com/josantonius/php-cookie/releases).

Contribution
------------

[](#contribution)

Please make sure to read the [Contributing Guide](.github/CONTRIBUTING.md), before making a pull request, start a discussion or report a issue.

Thanks to all [contributors](https://github.com/josantonius/php-cookie/graphs/contributors)! ❤️

Sponsor
-------

[](#sponsor)

If this project helps you to reduce your development time, [you can sponsor me](https://github.com/josantonius#sponsor) to support my open source work 😊

License
-------

[](#license)

This repository is licensed under the [MIT License](LICENSE).

Copyright © 2016-present, [Josantonius](https://github.com/josantonius#contact)

###  Health Score

48

—

FairBetter than 95% of packages

Maintenance35

Infrequent updates — may be unmaintained

Popularity40

Moderate usage in the ecosystem

Community19

Small or concentrated contributor base

Maturity80

Battle-tested with a long release history

 Bus Factor1

Top contributor holds 98.2% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~188 days

Total

16

Last Release

614d ago

Major Versions

1.1.6 → v2.0.02022-07-13

PHP version history (5 changes)1.0.0PHP &gt;=7.0

1.1.0PHP &gt;=5.6

1.1.1PHP ^5.6 || ^7.0

v2.0.0PHP ^8.0

v2.0.2PHP ^8.1

### Community

Maintainers

![](https://www.gravatar.com/avatar/4b221283501ec8a9cbaefaf27821a91ae8ddd33bddf1fccc6c6815b7ad216ff1?d=identicon)[Josantonius](/maintainers/Josantonius)

---

Top Contributors

[![josantonius](https://avatars.githubusercontent.com/u/18104336?v=4)](https://github.com/josantonius "josantonius (109 commits)")[![escannord](https://avatars.githubusercontent.com/u/109680430?v=4)](https://github.com/escannord "escannord (2 commits)")

---

Tags

cookiecookieshandling-cookiesphpphp-cookiephp-libraryphpcookies

###  Code Quality

TestsPHPUnit

Code StylePHP\_CodeSniffer

### Embed Badge

![Health badge](/badges/josantonius-cookie/health.svg)

```
[![Health](https://phpackages.com/badges/josantonius-cookie/health.svg)](https://phpackages.com/packages/josantonius-cookie)
```

###  Alternatives

[imanghafoori/laravel-anypass

A minimal yet powerful package to help you in development.

21421.6k](/packages/imanghafoori-laravel-anypass)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
