Soumik
Soumik

Reputation: 137

Cookie creation in zend framework 2

I need one help in creating cookie in zend framework 2.

I couldn't figure it out the correct way to implement it. I have tried to create cookie object and assign using code from Zend Http Client documentation.

This does not gives me error , so i assumed it that cookies has been created , but i couldn't assign time of expiration in it , and how to get this two cookie variable data which i have created and check whether this cookie exists.

I need help on these , If I have coded wrong then please show me the code to how to create a cookie and later check it whether it exists and then fetch the value from it?

Upvotes: 0

Views: 2632

Answers (2)

Soumik
Soumik

Reputation: 137

This my code to create , this might help others for zend framework 2 =>

$cookie1 = new \Zend\Http\Header\SetCookie('emailcookie', $email, time() + (((30*24)*60)*60));
$cookie2 = new \Zend\Http\Header\SetCookie('passwordcookie', $password, time() + (((30*24)*60)*60));

$this->getResponse()->getHeaders()->addHeader($cookie1);
$this->getResponse()->getHeaders()->addHeader($cookie2);

// For unsetting cookie:
$getcookie=$request->getCookie(); // returns object of Zend\Http\Header\Cookie

$chkemailcookieexist=$getcookie->offsetExists('emailcookie');

$chkpasswordcookieexist=$getcookie->offsetExists('passwordcookie');

// var_dump($chkemailcookieexist);
$prevdatetime=strtotime('-1 day', strtotime(date('Y-m-d')));

if($chkemailcookieexist)
{
    $cookie1 = new \Zend\Http\Header\SetCookie('emailcookie', $email,$prevdatetime);
    $this->getResponse()->getHeaders()->addHeader($cookie1);
}

// var_dump($chkpasswordcookieexist);
if($chkpasswordcookieexist)
{
    $cookie2 = new \Zend\Http\Header\SetCookie('passwordcookie', $password, $prevdatetime);
    $this->getResponse()->getHeaders()->addHeader($cookie2);
}

Upvotes: 1

lku
lku

Reputation: 1742

You can use SetCookie header class (Zend\Http\Header\SetCookie). For example in your controller:

$cookie = new SetCookie('cookieName', 'cookieValue', time() + 60 * 60 * 24 * 1);
$this->getResponse()->getHeaders()->addHeader($cookie);

Check the class constructor, you can set there all needed flags.

Then you can read cookies from Zend\Http\Request, for example in controller:

$cookieValue = $this->getRequest()->getCookie()->cookieName;

Where getCookie method returns Zend\Http\Header\Cookie which is ArrayObject and contains all cookies from request.

Upvotes: 0

Related Questions