Skip to content

josantonius/php-cookie

Repository files navigation

PHP Cookie library

Latest Stable Version License Total Downloads CI CodeCov PSR1 PSR4 PSR12

Translations: Español

PHP library for handling cookies.



Requirements

This library is compatible with the PHP versions: 8.1.

Installation

The preferred way to install this extension is through Composer.

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 Methods

Available methods in this library:

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.
 */

$cookie = new Cookie(
    string              $domain   = '',
    int|string|DateTime $expires  = 0,
    bool                $httpOnly = false,
    string              $path     = '/',
    bool                $raw      = false,
    null|string         $sameSite = null,
    bool                $secure   = false
);

@see https://www.php.net/manual/en/datetime.formats.php for supported date and time formats.

@throws CookieException if $sameSite value is wrong.

Sets a cookie by name

$cookie->set(
    string $name,
    mixed $value,
    null|int|string|DateTime $expires = null
): void

@throws CookieException if headers already sent.

@throws CookieException if failure in date/time string analysis.

Sets several cookies at once

If cookies exist they are replaced, if they do not exist they are created.

$cookie->replace(
    array $data,
    null|int|string|DateTime $expires = null
): void

@throws CookieException if headers already sent.

Gets a cookie by name

Optionally defines a default value when the cookie does not exist.

$cookie->get(string $name, mixed $default = null): mixed

Gets all cookies

$cookie->all(): array

Check if a cookie exists

$cookie->has(string $name): bool

Deletes a cookie by name and returns its value

Optionally defines a default value when the cookie does not exist.

$cookie->pull(string $name, mixed $default = null): mixed

@throws CookieException if headers already sent.

Deletes an cookie by name

$cookie->remove(string $name): void

@throws CookieException if headers already sent.

@throws CookieException if failure in date/time string analysis.

Quick Start

To use this class with Composer:

require __DIR__ . '/vendor/autoload.php';

Using objects

use Josantonius\Cookie\Cookie;

$cookie = new Cookie();

Using the facade

Alternatively you can use a facade to access the methods statically:

use Josantonius\Cookie\Facades\Cookie;

Usage

Example of use for this library:

- Sets cookie options

Using objects:

Without setting options:

$cookie = new Cookie();

Setting options:

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

Using the facade:

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

- Sets a cookie by name

Using objects:

Without modifying the expiration time:

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

Modifying the expiration time:

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

Using the facade:

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

- Sets several cookies at once

Using objects:

Without modifying the expiration time:

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

Modifying the expiration time:

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

Using the facade:

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

- Gets a cookie by name

Using objects:

Without default value if cookie does not exist:

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

With default value if cookie does not exist:

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

Using the facade:

Cookie::get('foo', false);

- Gets all cookies

Using objects:

$cookie->all();

Using the facade:

Cookie::all();

- Check if a cookie exists

Using objects:

$cookie->has('foo');

Using the facade:

Cookie::has('foo');

- Deletes a cookie by name and returns its value

Using objects:

Without default value if cookie does not exist:

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

With default value if cookie does not exist:

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

Using the facade:

Cookie::pull('foo', false);

- Deletes an cookie by name

Using objects:

$cookie->remove('foo');

Using the facade:

Cookie::remove('foo');

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

To run tests you just need composer and to execute the following:

git clone https://github.com/josantonius/php-cookie.git
cd php-cookie
composer install

Run unit tests with PHPUnit:

composer phpunit

Run code standard tests with PHPCS:

composer phpcs

Run PHP Mess Detector tests to detect inconsistencies in code style:

composer phpmd

Run all previous tests:

composer tests

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

Detailed changes for each release are documented in the release notes.

Contribution

Please make sure to read the Contributing Guide, before making a pull request, start a discussion or report a issue.

Thanks to all contributors! ❤️

Sponsor

If this project helps you to reduce your development time, you can sponsor me to support my open source work 😊

License

This repository is licensed under the MIT License.

Copyright © 2016-present, Josantonius

About

PHP library for handling cookies

Topics

Resources

License

Code of conduct

Contributing

Stars

Watchers

Forks

Sponsor this project

 

Packages

No packages published

Contributors 2

  •  
  •  

Languages