6

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?

6

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);
| improve this answer | |
  • Here is a conveniently written plugin that does just that: straightupcraft.com/craft-plugins/lj-cookies – Brad Bell Jul 1 '14 at 19:18
  • Perfect, craft()->userSession->saveCookie and craft()->userSession->getCookieValue is what I was looking for. – Tim Kelty Jul 2 '14 at 11:14
  • @BradBell that plugin just uses setcookie, I was looking to make it work with the craft()->security checks. – Tim Kelty Jul 2 '14 at 11:16
5

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

...enjoy.

| improve this answer | |
  • 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 Jun 16 '15 at 18:02
  • I'd use JavaScript for that – andrew.welch May 20 '18 at 21:43
2

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.
Craft::$app->getResponse()->getCookies()->add($cookie);

To get the cookie's value, use:

Craft::$app->request->cookies->get('CookiesAccepted');
| improve this answer | |
1

To access a cookie you can use the plugin variable class

<?php

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') %}

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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