elephpant/cookie

处理Cookies的简单有效方式

2.0.2 2023-05-28 18:43 UTC

This package is auto-updated.

Last update: 2024-09-28 22:14:55 UTC


README

Maintainer Source Code PHP from Packagist Latest Version Software License Build Quality Score Total Downloads

安装

Composer(推荐)

使用Composer从Packagist安装此库:elephpant/cookie

从您的项目目录运行以下命令以添加依赖项

composer require elephpant/cookie "^2.0"

或者,直接将依赖项添加到您的composer.json文件中

"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);
创建Cookie
$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);
获取Cookie(s)
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.';
}

贡献

工程师永远都不够多,因此我们非常乐意接受通过Pull Requests的贡献。有关详细信息,请参阅CONTRIBUTING

鸣谢

许可协议

MIT许可协议(MIT)。请参阅许可文件以获取更多信息。