A more elegant solution since PHP >=7.0
session_start(['cookie_lifetime' => 43200,'cookie_secure' => true,'cookie_httponly' => true]);
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 );
Explanation here from Ilia... 5.2 only though
httpOnly cookie flag support in PHP 5.2
As stated in that article, you can set the header yourself in previous versions of PHP
header("Set-Cookie: hidden=value; httpOnly");
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:
session_name()
before session_start()
You can specify it in the set cookie function see the php manual
setcookie('Foo','Bar',0,'/', 'www.sample.com' , FALSE, TRUE);
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.
The right syntax of the php_flag command is
php_flag session.cookie_httponly On
And be aware, just first answer from server set the cookie and here (for example You can see the "HttpOnly" directive. So for testing delete cookies from browser after every testing request.
<?php
//None HttpOnly cookie:
setcookie("abc", "test", NULL, NULL, NULL, NULL, FALSE);
//HttpOnly cookie:
setcookie("abc", "test", NULL, NULL, NULL, NULL, TRUE);
?>
You can use this in a header file.
// setup session enviroment
ini_set('session.cookie_httponly',1);
ini_set('session.use_only_cookies',1);
This way all future session cookies will use httponly.
Source: Stackoverflow.com