Creating a Cookie
For example to create a cookie called “my_cookie”, we could use the following code:
$cookie = new Cookie( 'my_cookie', // Cookie name. $obj->getValue(), // Cookie value. time() + ( 2 * 365 * 24 * 60 * 60) // Expires 2 years. );
In the above code. The second parameter of the Cookie is the value, and in the example I use the object’s “getValue” function to set the value of the cookie. The 3rd parameter of the cookie is the time, and is the time that the cookie will expire. In my example, the “time()” function gets the current time, and then add 2 years to current time.
Sending a Cookie
In order to send a cookie to a client, we need to use a “Response” and set the cookie in the header. At the top of your file you’ll need to add both the Cookie and Response use statements like so:
use Symfony\Component\HttpFoundation\Cookie; use Symfony\Component\HttpFoundation\Response;
Then create a new Response object and send the above cookie like so:
$res = new Response(); $res->headers->setCookie( $cookie ); $res->send();
The client will now have the cookie you sent. After this you can do other things like redirect or process other code in your Controller.
The following example deletes the cookie called “my_old_cookie”; it also uses a response to do this:
$res = new Response(); $res->headers->clearCookie('my_old_cookie'); $res->send();
After this you can do various other processing of code.
I hope this helps someone!