siteparts / http-message-cookies
Cookies for PSR-7
v1.0.0
2023-08-23 15:30 UTC
Requires
- php: ^7.1 || ^8.0
- psr/http-message: ^1.0 || ^2.0
Requires (Dev)
- phpstan/phpstan: ^1.10
Suggests
- psr/container: ^1.0 || ^2.0 to use the factory
This package is auto-updated.
Last update: 2024-10-23 18:22:44 UTC
README
Add cookie headers to PSR-7 messages.
Installation
Via Composer:
$ composer require siteparts/http-message-cookies
Usage
The Set-Cookie
headers are added to the PSR-7 response object using the
addTo
method of ResponseCookie
class.
Set cookies using template:
use DateTime; use SiteParts\Cookies\HttpMessage\ResponseCookieTemplate; $cookieTemplate = new ResponseCookieTemplate([ 'domain' => 'example.org', 'path' => '/foo', 'expires' => new DateTime("+14 days"), ]); // $response is instance of Psr\Http\Message\ResponseInterface $response = $cookieTemplate ->create("lang", "en") ->addTo($response); $response = $cookieTemplate ->create("color", "blue") ->withSecure(true) ->addTo($response);
Set cookies directly:
use DateTime; use SiteParts\Cookies\HttpMessage\ResponseCookie; // $response is instance of Psr\Http\Message\ResponseInterface $response = new ResponseCookie("lang", "en") ->withDomain("example.org") ->withPath("/foo") ->withExpires(new DateTime("+14 days")) ->addTo($response); $response = new ResponseCookie("color", "blue") ->withDomain("example.org") ->withPath("/foo") ->withExpires(new DateTime("+14 days")) ->withSecure(true) ->addTo($response);
Response cookie template parameters:
$cookieTemplate = new ResponseCookieTemplate([ 'domain' => 'example.org', 'path' => '/foo', 'expires' => new DateTime("+14 days"), 'max_age' => 14 * 24 * 60 * 60, 'secure' => true, 'http_only' => true, 'same_site' => 'Strict', ]);
Response cookie methods:
$cookie = new ResponseCookie("lang", "en") ->withDomain("example.org") ->withPath("/foo") ->withExpires(new DateTime("+14 days")) ->withMaxAge(14 * 24 * 60 * 60) ->withSecure(true) ->withHttpOnly(true) ->withSameSite("Strict");
For use with a PSR-11 container, see ResponseCookieTemplateFactory
class.