1

I have some data I want to store in session:

$data = array
(
    'id' => '23539471'
    'token' => 'cf310b81-9431-4303-804d-c1635ae29278'
);

In my plugin I am doing this:

new HttpCookie('myCookieName', $data, [ 'expire' => time() + 3600 ]);

When I dd() that I can see the cookie as expected:

Craft\HttpCookie#1
(
    [name] => 'myCookieName'
    [value] => array
    (
        'id' => '23539471'
        'token' => 'cf310b81-9431-4303-804d-c1635ae29278'
    )
    [domain] => ''
    [expire] => 1427328767
    [path] => '/'
    [secure] => true
    [httpOnly] => true
    [CComponent:_e] => null
    [CComponent:_m] => null
)

However on the next page load the cookie is null:

$cookie = craft()->request->getCookie('myCookieName');

What am I doing wrong here?

::::EDIT::::

I have also tried this which seems to make the cookie available in the current request, but it's null on the next request:

$cookie = new HttpCookie('myCookieName', $data);
$cookie->expire = time() + 3600;

craft()->request->cookies->add('myCookieName', $cookie);
  • I should add that I am on a secure HTTPS page when setting this (the whole site is on HTTPS). – Russ Back Mar 25 '15 at 23:18
3

Try this:

$cookie = new HttpCookie('myCookieName', $data, [ 'expire' => time() + 3600 ]);
craft()->request->getCookies()->add( $cookie->name, $cookie );

Your code for reading the cookie is fine.

Also – since you use the term "session value" and tagged your question w/ "security" – I'd like to point out that cookies and session variables are different things. The former is stored on the client (the browser), the latter only on the server.

Unless you specifically need a cookie (e.g. because you want the data to persist a certain amount of time) it might be better to just create a basic session variable, using the HttpSession service:

craft()->httpSession->add( $key, $value ); // Set the session variable
craft()->httpSession->get( $key ); // Get the session variable

Read more about session variables vs. cookies here

  • Perfect - thanks. A session var is exactly what I need. – Russ Back Mar 25 '15 at 23:47

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.