During my current project upgrade from TYPO3 13 LTS to TYPO3 14 LTS, I stumbled upon a problem: a cookie could no longer be set.
The old way #
My old way was pretty simple and, I guess, the usual way most PHP developers set cookies: PHP's setcookie() function.
setcookie('cookiename', 'my cookie value', $options);
I did not investigate in detail why this does not work anymore in TYPO3 14 LTS. But to make it more complicated, I can say: "It depends". Because some of my cookies were still set correctly, while others were no longer. 🤷♂️
The new way #
I refactored my code to manually add a Set-Cookie header to the HTTP response. In simplified form, I do something like this
in a middleware:
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
$response = $handler->handle($request);
return $response->withAddedHeader('Set-Cookie', 'cookiename=my cookie value');
}
But wait ... this is pretty ugly and prone to errors. Aren't there any ways to prevent syntax errors or help developers
to set all necessary options? Sure there are! 🤓 You can use Symfony's cookie component. Just build your cookie based
on Symfony\Component\HttpFoundation\Cookie, cast it as a string, and you're done:
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
$response = $handler->handle($request);
$cookie = new Symfony\Component\HttpFoundation\Cookie(
'cookiename',
'my cookie value',
path: '/',
sameSite: 'strict'
);
return $response->withAddedHeader('Set-Cookie', (string)$cookie);
}
There are many more configuration options. You can see them all directly in Symfony's source code