Introduction

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

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, is 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 Symfony application I was creating a cookie something like this:

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

$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.