An open API service indexing awesome lists of open source software.

https://github.com/arraypress/wp-cookie-utils

A lean PHP library for WordPress cookie management with secure defaults, multisite support, type casting, and essential cookie operations.
https://github.com/arraypress/wp-cookie-utils

Last synced: 4 months ago
JSON representation

A lean PHP library for WordPress cookie management with secure defaults, multisite support, type casting, and essential cookie operations.

Awesome Lists containing this project

README

          

# WordPress Cookie Utilities

A lean PHP library for managing cookies in WordPress, providing secure cookie handling, multisite support, type casting, and essential cookie operations.

## Features

- 🔒 **Secure by Default**: Built with security best practices
- 🌐 **Multisite Support**: Handle cookies across WordPress multisite networks
- 🎯 **Type Casting**: Get cookie values with automatic type conversion
- ⏱️ **Time Utilities**: Convenient methods for setting cookie expiration times
- 🔄 **Multiple Operations**: Set and manage multiple cookies at once
- 📦 **JSON Support**: Built-in JSON encoding and decoding
- ⚡ **WordPress Integration**: Seamless integration with WordPress functions
- 🔄 **Cookie Refresh**: Update expiration times without changing values
- ✅ **Size Validation**: Automatic cookie size limit checking
- 🎛️ **SameSite Control**: Full control over SameSite cookie attributes

## Requirements

- PHP 7.4 or later
- WordPress 5.0 or later

## Installation

Install via Composer:

```bash
composer require arraypress/wp-cookie-utils
```

## Basic Usage

### Setting Cookies

```php
use ArrayPress\CookieUtils\Cookie;

// Set a basic cookie
Cookie::set( 'my_cookie', 'cookie_value' );

// Set a cookie with expiration time
Cookie::set( 'my_cookie', 'value', Cookie::hours( 2 ) ); // Expires in 2 hours

// Set a secure cookie with WordPress defaults
Cookie::set_secure( 'my_cookie', 'cookie_value' );
```

### Time Utilities

```php
// Individual time methods
Cookie::set( 'seconds_cookie', 'value', Cookie::seconds( 30 ) ); // 30 seconds
Cookie::set( 'minutes_cookie', 'value', Cookie::minutes( 15 ) ); // 15 minutes
Cookie::set( 'hours_cookie', 'value', Cookie::hours( 2 ) ); // 2 hours
Cookie::set( 'days_cookie', 'value', Cookie::days( 7 ) ); // 7 days
Cookie::set( 'weeks_cookie', 'value', Cookie::weeks( 2 ) ); // 2 weeks
Cookie::set( 'months_cookie', 'value', Cookie::months( 6 ) ); // 6 months
Cookie::set( 'years_cookie', 'value', Cookie::years( 1 ) ); // 1 year

// Unified time method
Cookie::set( 'flexible_cookie', 'value', Cookie::from_now( 3, 'hours' ) );
Cookie::set( 'another_cookie', 'value', Cookie::from_now( 14, 'days' ) );
```

### Getting Cookie Values

```php
// Get a cookie value
$value = Cookie::get( 'my_cookie' );

// Get with default value if cookie doesn't exist
$value = Cookie::get( 'my_cookie', 'default_value' );

// Check if a cookie exists
if ( Cookie::exists( 'my_cookie' ) ) {
// Cookie exists
}
```

### Type Casting

```php
// Get cookie values with automatic type casting
$count = Cookie::get_cast( 'item_count', 'int', 0 );
$enabled = Cookie::get_cast( 'feature_enabled', 'bool', false );
$tags = Cookie::get_cast( 'selected_tags', 'array', [] );
$price = Cookie::get_cast( 'product_price', 'float', 0.0 );
$name = Cookie::get_cast( 'user_name', 'string', '' );

// Supported types: 'int', 'integer', 'float', 'double', 'bool', 'boolean', 'array', 'string'
```

### Working with JSON Data

```php
// Set a cookie with JSON data
$data = [ 'key' => 'value', 'array' => [ 1, 2, 3 ] ];
Cookie::set_json( 'json_cookie', $data );

// Get and decode JSON data
$data = Cookie::get_json( 'json_cookie', [] );
```

### Multisite Support

```php
// Set a cookie for the current site in multisite
Cookie::set_multisite( 'site_cookie', 'site_value', false ); // Site-specific

// Set a network-wide cookie
Cookie::set_multisite( 'network_cookie', 'network_value', true ); // Network-wide
```

### Multiple Cookie Operations

```php
// Set multiple cookies at once
$cookies = [
'cookie1' => 'value1',
'cookie2' => 'value2',
'cookie3' => 'value3'
];
Cookie::set_multiple( $cookies, Cookie::days( 1 ) );

// Delete multiple cookies
$names = [ 'cookie1', 'cookie2', 'cookie3' ];
Cookie::delete_multiple( $names );
```

### Cookie Management

```php
// Refresh a cookie's expiration without changing its value
Cookie::refresh( 'session_token', Cookie::hours( 1 ) );

// Check if a cookie value is within size limits
if ( Cookie::is_valid_size( $large_value ) ) {
Cookie::set( 'large_cookie', $large_value );
}

// Delete a specific cookie
Cookie::delete( 'unwanted_cookie' );

// Get all cookies
$all_cookies = Cookie::get_all();
```

## Advanced Options

### Custom Cookie Options

```php
$options = [
'expire' => Cookie::days( 7 ), // 7 days
'path' => '/custom/path',
'domain' => 'example.com',
'secure' => true,
'httponly' => true,
'samesite' => Cookie::SAMESITE_LAX // LAX, STRICT, or NONE
];

Cookie::set_secure( 'custom_cookie', 'value', $options );
```

### SameSite Attribute Options

```php
// Strict (default) - Most secure, blocks all cross-site requests
Cookie::set_secure( 'csrf_token', $token, [
'samesite' => Cookie::SAMESITE_STRICT
] );

// Lax - Allows some cross-site requests (good for auth cookies)
Cookie::set_secure( 'auth_token', $token, [
'samesite' => Cookie::SAMESITE_LAX
] );

// None - Allows all cross-site requests (requires Secure flag)
Cookie::set_secure( 'widget_state', $state, [
'samesite' => Cookie::SAMESITE_NONE,
'secure' => true // Required with NONE
] );
```

## Common Use Cases

### Authentication Cookies

```php
// Set login cookie with appropriate settings
Cookie::set_secure( 'user_session', $session_token, [
'expire' => Cookie::hours( 24 ),
'samesite' => Cookie::SAMESITE_LAX,
'httponly' => true,
'secure' => true
] );
```

### User Preferences

```php
// Store user preferences as JSON
$preferences = [
'theme' => 'dark',
'language' => 'en',
'notifications' => true
];
Cookie::set_json( 'user_prefs', $preferences, [
'expire' => Cookie::months( 6 )
] );

// Retrieve preferences with type casting
$theme = Cookie::get_cast( 'selected_theme', 'string', 'light' );
$notifications = Cookie::get_cast( 'notifications_enabled', 'bool', true );
```

### Shopping Cart State

```php
// Store cart items
$cart_items = [ 'item1', 'item2', 'item3' ];
Cookie::set_json( 'cart_items', $cart_items );

// Get cart count
$cart_count = Cookie::get_cast( 'cart_count', 'int', 0 );

// Refresh cart session
Cookie::refresh( 'cart_session', Cookie::hours( 2 ) );
```

## Security Features

- Automatic value sanitization using `wp_kses`
- RFC-compliant cookie name validation
- SameSite attribute enforcement (Strict by default)
- HTTPOnly flag enabled by default
- Secure flag enabled by default for HTTPS
- Automatic size validation (4096 byte limit)
- Graceful error handling without logging

## Best Practices

1. **Use secure defaults**: Always prefer `Cookie::set_secure()` over `Cookie::set()`
2. **Set appropriate expiration**: Don't use excessively long expiration times
3. **Use type casting**: Leverage `get_cast()` for consistent data types
4. **Choose correct SameSite**: Use `LAX` for auth, `STRICT` for security, `NONE` for embeds
5. **Validate before setting**: Use `is_valid_size()` for large values
6. **Clean up**: Delete cookies when no longer needed

## Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

## License

This project is licensed under the GPL-2.0-or-later License.

## Support

- [Documentation](https://github.com/arraypress/wp-cookie-utils)
- [Issue Tracker](https://github.com/arraypress/wp-cookie-utils/issues)