setCookie

The setCookie hook is triggered when sending a cookie to the browser. It passes a standard object with all cookie properties and expects the same as return value.

Parameters

  1. object $cookie

    A stdClass instance that contains the properties of the cookie. See PHP’s setcookie documentation for detailed information.

    • $cookie->strName – the cookie name
    • $cookie->varValue – the cookie value
    • $cookie->intExpires – the expiration time (in seconds, from now)
    • $cookie->strPath – the relative path (if Contao is installed in a subfolder)
    • $cookie->strDomain – the current domain for the cookie
    • $cookie->blnSecure – if the cookie should only be stored for https access
    • $cookie->blnHttpOnly – if the httponly flag should be set

Return Values

Return $cookie or a custom object with all properties.

Example

// src/EventListener/SetCookieListener.php
namespace App\EventListener;

use Contao\CoreBundle\ServiceAnnotation\Hook;
use Terminal42\ServiceAnnotationBundle\ServiceAnnotationInterface;

class SetCookieListener implements ServiceAnnotationInterface
{
    /**
     * @Hook("setCookie")
     */
    public function onSetCookie($cookie): object
    {
        // Make sure the cookie is also valid for the whole domain
        $cookie->strPath = '/';

        return $cookie;
    }
}

References