HTTP Cookies in Symfony


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',	// 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.

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 using 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!

Advertisements

About Alvin Bunk
Hi, I'm a software developer at Taft College.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: