Introduction
There are a number of times I’ve had to use HTTP cookies for some of the Symfony projects I’ve developed at Taft College. There is some documentation on using cookies, but you really need to look at either the API documentation or search online for various references to get good examples on how to use cookies properly. Thus I’m writing this article so that some people might use it as a reference.
Creating a Cookie
For example, to create a cookie called “my_cookie
”, we could use the following code:
$cookie = new Cookie(
'my_cookie',
$obj->getValue(),
time() + ( 2 * 365 * 24 * 60 * 60)
);
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 adds 2 years to the 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.
Deleting Cookies
A lot of times, you will want to clean up cookies. For example, you use a temporary cookie let’s say in JavaScript, and then later you want to delete it, because it was only used to control various functions.
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!