How do you set up use HttpOnly cookies in PHP


Question

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

1
88
6/5/2015 10:09:07 PM

Accepted Answer

  • 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 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 )

Enter NULL for parameters you wish to remain as default. You may also want to consider if you should be setting the secure parameter.

It is also possible using the older, lower-level header() function:

header( "Set-Cookie: name=value; httpOnly" );
83
5/23/2017 12:03:06 PM

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 );

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon