Use Composer to install this library from Packagist:
elephpant/cookie
Run the following command from your project directory to add the dependency:
composer require elephpant/cookie "^2.0"
Alternatively, add the dependency directly to your composer.json
file:
"require": {
"elephpant/cookie": "^2.0"
}
<?php
use ElePHPant\Cookie\Cookie\Cookie;
// default expiration: minutes
// default encryption: there is no encryption
$cookie = new Cookie();
// change expiration unit
$options = [
'expiration' => 'days', // seconds, minutes, hours, days, weeks, months, years
];
// set Base64 encryption
$options = [
'encryption' => \ElePHPant\Cookie\Strategies\Encryption\Base64EncryptionStrategy::class,
];
// set AES-256 encryption
$options = [
'encryption' => \ElePHPant\Cookie\Strategies\Encryption\AES256EncryptionStrategy::class,
'encrypt_key' => 'SET_YOUR_ENCRYPT_KEY_HERE', // required if using AES-256
];
// other optional parameters
$options['path'] = '/';
$options['domain'] = '';
$options['secure'] = false;
$options['httponly'] = false;
// SameSite
$options['samesite'] = 'None'; // must be 'None', 'Lax' or 'Strict'. If none requires secure true
$options['secure'] = true; // required if samesite is 'None'
$cookie = new Cookie($options);
$str = 'john_doe';
$arr = ['name' => 'John Doe', 'email' => 'john@example.com', 'age' => 30,];
// name, value(s), expiration, ...
$cookie::set('username', $str, 20);
$cookie::set('user', $arr, 20);
echo $cookie::get('username'); // john_doe
$arr = $cookie::get('user');
var_export($arr); // array ( 'name' => 'John Doe', 'email' => 'john@example.com', 'age' => 30, )
echo $arr['email']; // john@example.com
$all = $cookie::get();
var_export($all); // array ( 'username' => 'john_doe', 'user' => array ( 'name' => 'John Doe', 'email' => 'john@example.com', 'age' => 30, ), )
var_export($_COOKIE); // array ( 'username' => '9sV1OIHc7taGoafeXWjl+gcrJFpIpg8Hkqe4fdGRygI=', 'user' => 'rLrCW9eBvoPijA+bSuIIrqbWccbYJqk2aPK5RGMwiLNpMZw2nYrrU7A2Zmuk3CGt0XiXlXpcQQv7h40M/6jbYslrlsvTJXm3mtG0nyiRDCg=', )
$cookie::setDoesntHave('cookie_consent', true, 60);
$cookie::setDoesntHave('toggle_sidebar', true, 60, true);
$cookie::destroy('user');
$cookie::destroy(); // all
if ($cookie::has('food')) {
echo 'The cookie exists.';
} else {
echo 'The cookie does not exist.';
}
if ($cookie::has('username', $str)) {
echo 'The cookie exists with the correct value.';
} else {
echo 'The cookie does not exist or has a different value.';
}
if ($cookie::has('user', $arr)) {
echo 'The cookie exists with the correct value.';
} else {
echo 'The cookie does not exist or has a different value.';
}
No one ever has enough engineers, so we're very happy to accept contributions via Pull Requests. For details, see CONTRIBUTING
- Wilder Amorim (Developer)
- All Contributors (This Rock)
The MIT License (MIT). Please see License File for more information.