Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / PHP

Create Symfony Cookie and Set HttpOnly to False

4.00/5 (1 vote)
19 Jun 2017CPOL1 min read 7.9K  
Create Symfony Cookie and set HttpOnly to false

Introduction

Recently, I tried to get cookies from the DOM using the following code:

JavaScript
var cookies = document.cookie.split('; ');

I noticed every time, the "document.cookie" value was a blank string, and I was scratching my head trying to figure out how such a thing could happen.

Then I happen to stumble upon that there is a HttpOnly parameter that can be set and this was the root cause.

HttpOnly Usage

So what’s the purpose of the HttpOnly flag? According to this Coding Horror post, it was introduced in the IE6 SP1 browser as part of a plan to reduce XSS. Actually, it is really a good idea, since with the HttpOnly flag set to true, any JavaScript code will not be able to access the cookie.

Symfony Defaults

Unfortunately, the Symfony cookie defaults to true. In my application, I was creating a cookie something like this:

JavaScript
$cookie = new Cookie(
   'my_cookie',                       // Name
   $obj->getId(),                     // Value
   time() + ( 2 * 365 * 24 * 60 * 60) // Expires 2 years
);

If you look at the Symfony Cookie construct documentation, you’ll see the default of $httpOnly is true; so given the above code, the HttpOnly flag will be set to true.

Create With HttpOnly Set to False

If you need to set the HttpOnly flag to false, you’ll need to code something like this:

JavaScript
$cookie = new Cookie(
   'my_cookie',
   $obj->getId(),
   time() + ( 2 * 365 * 24 * 60 * 60),
   '/',      // Path.
   null,     // Domain.
   false,    // Xmit secure https.
   false     // HttpOnly Flag.
);

Some values of the above I just set to common sense values, and in particular, the HttpOnly flag is set. Once this is done, you can now do things like delete the cookie or change it as needed.

Hope this helps someone out.

License

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