views:

1971

answers:

6

How can I set the cookies in my PHP apps as HttpOnly cookies?

+2  A: 

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");
Flubba
A: 
<?php
//None HttpOnly cookie:
setcookie("abc", "test", NULL, NULL, NULL, NULL, FALSE); 

//HttpOnly cookie:
setcookie("abc", "test", NULL, NULL, NULL, NULL, TRUE); 

?>

Source

Marius
A: 

You can specify it in the set cookie function see the php manual

setcookie('Foo','Bar',0,'/', 'www.sample.com'  , FALSE, TRUE);
Re0sless
+17  A: 

When setting cookies manually, use the following parameter syntax to the header() function:

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

However, if you have PHP 5.2.0 or greater, then you can use the setcookie() and setrawcookie() functions. Simply set the 7th parameter to true, as per the syntax

setcookie(    $name, $value, $expire, $path, $domain, $secure, $httponly )
setrawcookie( $name, $value, $expire, $path, $domain, $secure, $httponly )

(function syntax simplified for brevity). Enter NULL for parameters you wish to remain as default.

Please note that versions of PHP before 5.2.0 do have the setcookie functions, but the httpOnly parameter was not yet introduced.

Cheekysoft
+7  A: 

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.

tqbf
+2  A: 

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() before session_start()
  • This also sets the default path to '/', which is necessary for Opera but which PHP session cookies don't do by default either.