0

I'm struggling with this, I need to store data in the browser's cache. I'm using Symfony 2.6.1, I use the following code:

 if($request->cookies->get('myCookie')){ /* do stuff */ }else{ $cookie = new Cookie('myCookie', $myData, 0, '/', null, false, false); $response->headers->setCookie($cookie); $response->setCache(array( 'etag' => 'abcdef', 'last_modified' => new \DateTime(), 'max_age' => 600, 's_maxage' => 600, // 'private' => false, 'public' => true, )); $response->send(); /* send a response */ } 

I need to 1st check if the cookie "myCookie" exists, if not it should create and store in the browser. My problem is that, when I simply refresh the page to cookie is there, but if I close the browser, when I open again the cookie is not there.

I think that is some configuration/ propriety in the in the array when I set the cookie $response->setCache(array( ... ))

In the official site, there is not many helpful info about this.

http://symfony.com/doc/current/book/http_cache.html#types-of-caches

2
  • Why don't you just save it within the session? And is it neccessary to save the data after the browser got closed? Commented Apr 14, 2015 at 11:33
  • Yes, that data should stay in the cache's browser. When ever the user opens the site, I should be able to read the data stored and act accordingly. Commented Apr 14, 2015 at 11:45

1 Answer 1

2

Cookie being gone actually makes sense. You're constructing the cookie with line:

$cookie = new Cookie('myCookie', $myData, 0, '/', null, false, false); 

The third argument (0) means that it's a session cookie - will be discarded as soon as you close your browser.

Try something like this:

// Cookie stays alive for an hour $cookie = new Cookie('myCookie', $myData, time() + 3600, '/', null, false, false); 
Sign up to request clarification or add additional context in comments.

2 Comments

I'hav tried that now, if i use 3600 instead of 0, it won't create a cookie.
My mistake, sorry about that. The number should not be relative but absolute instead. Try putting time() + 3600....

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.