Implementing HTTPOnly in PHP

Coding Horror has an article today about a little-known extension to the http cookie protocol: HTTPOnly.

Essentially, HTTPOnly makes any browser cookies from the site unreadable to javascript (in supported browsers anyway: IE7, Opera 9.5, FF3), thus raising the bar for XSS attacks considerably.

So how do we turn it on in PHP? <!-- more -->

If you're using a version of PHP pre5.2:

header("Set-Cookie: hidden=value; httpOnly");

If you're using a new version of PHP (5.2+):

//Either of these options set the $_SESSION cookie into HTTPOnly mode
ini_set("session.cookie_httponly", 1);
// or
session_set_cookie_params(0, NULL, NULL, NULL, TRUE);

//Individual cookies can be set using:
setcookie("abc", "test", NULL, NULL, NULL, NULL, TRUE); 
setrawcookie("abc", "test", NULL, NULL, NULL, NULL, TRUE); 

And that's it! One simple line of code (or function argument) that you can add to your header file that helps makes attacks on your site tougher to execute.

Code snippets courtesy of Ilia Alshanetsky