PHP code example of initphp / cookies

1. Go to this page and download the library: Download initphp/cookies library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

initphp / cookies example snippets




use InitPHP\Cookies\Cookie;

// The salt is the HMAC secret. Keep it private and stable across requests.
$cookie = new Cookie('app_session', getenv('COOKIE_SALT'));

$cookie->set('user_id', 42);
$cookie->set('flash', 'Saved!', 60); // expires in 60 seconds

// Flush the staged changes to the browser before any output is sent.
$cookie->send();

$cookie = new Cookie('app_session', getenv('COOKIE_SALT'));

$cookie->has('user_id');     // true
$cookie->get('user_id');     // 42 (int — scalar types are preserved)
$cookie->get('missing', '-'); // '-' (default)
$cookie->pull('flash');      // reads the value once, then removes it

$cookie = new Cookie('app_session', $salt, [
    'ttl'      => 2592000, // transport-cookie lifetime in seconds (30 days)
    'path'     => '/',
    'domain'   => null,
    'secure'   => false,
    'httponly' => true,
    'samesite' => 'Strict', // 'Strict' | 'Lax' | 'None'
]);

public function has(string $key): bool;
public function get(string $key, mixed $default = null): mixed;
public function pull(string $key, mixed $default = null): mixed;
public function set(string $key, string|int|float|bool $value, ?int $ttl = null): self;
public function setArray(array $assoc, ?int $ttl = null): self;
public function push(string $key, string|int|float|bool $value, ?int $ttl = null): mixed;
public function all(): array;
public function remove(string ...$key): self;
public function send(): bool;
public function flush(): bool;
public function destroy(): bool;