Introduction
Recently, I tried to get cookies from the DOM using the following 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, 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:
$cookie = new Cookie(
'my_cookie',
$obj->getId(),
time() + ( 2 * 365 * 24 * 60 * 60)
);
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),
'/',
null,
false,
false
);
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.