How do you set up use HttpOnly cookies in PHP
How can I set the cookies in my PHP apps
as HttpOnly cookies
?
For PHP's own session cookies on Apache:
add this to your Apache configuration or .htaccess
<IfModule php5_module>
php_flag session.cookie_httponly on
</IfModule>
This can also be set within a script, as long as it is called before session_start()
.
ini_set( 'session.cookie_httponly', 1 );
- For your cookies, see this answer.
- For PHP's own session cookie (
PHPSESSID
, by default), see @richie's answer
The setcookie()
and setrawcookie()
functions, introduced the boolean httponly
parameter, back in the dark ages of PHP 5.2.0, making this nice and easy. Simply set the 7th parameter to true, as per the syntax
Function syntax simplified for brevity
setcookie( $name, $value, $expire, $path, $domain, $secure, $httponly )
setrawcookie( $name, $value, $expire, $path, $domain, $secure, $httponly )
In PHP < 8, specify NULL
for parameters you wish to remain as default.
In PHP >= 8 you can benefit from using named parameters. See this question about named params.
setcookie( $name, $value, httponly:true )
It is also possible using the older, lower-level header()
function:
header( "Set-Cookie: name=value; HttpOnly" );
You may also want to consider if you should be setting the Secure
parameter.
Note that PHP session cookies don't use httponly
by default.
To do that:
$sess_name = session_name();
if (session_start()) {
setcookie($sess_name, session_id(), null, '/', null, null, true);
}
A couple of items of note here:
- You have to call
session_name()
beforesession_start()
- This also sets the default path to '/', which is necessary for Opera but which PHP session cookies don't do by default either.
Be aware that HttpOnly doesn't stop cross-site scripting; instead, it neutralizes one possible attack, and currently does that only on IE (FireFox exposes HttpOnly cookies in XmlHttpRequest, and Safari doesn't honor it at all). By all means, turn HttpOnly on, but don't drop even an hour of output filtering and fuzz testing in trade for it.