Click here to Skip to main content
15,888,116 members
Articles / All Topics

HTTP Cookies in Symfony

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
3 Apr 2017CPOL2 min read 10.2K  
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:

PHP
$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 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:

PHP
$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:

PHP
$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!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer Taft College
United States United States
I’m a software developer. Currently I’m working at Taft College as a Programmer.

Comments and Discussions

 
-- There are no messages in this forum --