From either a plugin or a Twig template, is there a prescribed way to set (and get) cookies?

I've seen https://github.com/lewisjenkins/craft-lj-cookies/, which just uses PHP's setcookie.

Also noticed getCookie in craft.request. https://craftcms.com/docs/templating/craft.request#getCookie

I've noticed the cookies set with setcookie aren't readable by getCookie. How should one set a cookie so that it is readable by getCookie?

4 Answers 4


Cookies cannot be set via templates. However, in a plugin you have access to Craft's services. The UserSessionService has the saveCookie function.

craft()->userSession->saveCookie($cookieName, $data, $duration);
  • Here is a conveniently written plugin that does just that: straightupcraft.com/craft-plugins/lj-cookies
    – Brad Bell
    Commented Jul 1, 2014 at 19:18
  • Perfect, craft()->userSession->saveCookie and craft()->userSession->getCookieValue is what I was looking for.
    – Tim Kelty
    Commented Jul 2, 2014 at 11:14
  • @BradBell that plugin just uses setcookie, I was looking to make it work with the craft()->security checks.
    – Tim Kelty
    Commented Jul 2, 2014 at 11:16

I wrote a plugin similar to lj_cookies that accomplishes this for both regular and craft secure cookies:


  • 1
    Is it possible to use this on a click event? I want to set some cookies on CTA's and trying to think of a way to handle that.
    – Bowenac
    Commented Jun 16, 2015 at 18:02
  • I'd use JavaScript for that Commented May 20, 2018 at 21:43

In the new Craft 3, you can use the following in your plugin:

// Create cookie object.
$cookie = Craft::createObject([
    'class' => 'yii\web\Cookie',
    'name' => 'CookiesAccepted', 
    'httpOnly' => true,
    'value' => 'true',
    'expire' => time() + (86400 * 365),

// Set cookie.

To get the cookie's value, use:


To access a cookie you can use the plugin variable class


namespace Craft;

 * Class PluginVariable
 * @package Craft
class PluginVariable
     * Get the cookie value
     * @param string $name
     * @return string
    public function getPluginCookie($name)
        return $_COOKIE[$name] ?? '';

And inside your twig file you call

{% set pluginCookie = craft.plugin.getPluginCookie('some_cookie_name') %}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.