How to Make Cookies HttpOnly in PHP
Setting the HttpOnly flag on cookies is a crucial
security practice that prevents client-side scripts, such as JavaScript,
from accessing cookie data. By blocking this access, you significantly
mitigate the risk of session hijacking through Cross-Site Scripting
(XSS) attacks. This article provides a straightforward guide on how to
configure secure, HTTP-only cookies in PHP for both standard cookies and
session-based cookies.
Method 1: Using the
setcookie() Function
PHP’s native setcookie() function allows you to define
cookie attributes. The modern, recommended way (available since PHP 7.3)
is to pass an associative array of options as the third argument.
Here is how to set an HttpOnly cookie using the options array:
setcookie("user_session", "secure_token_value", [
'expires' => time() + 3600, // Expires in 1 hour
'path' => '/',
'domain' => 'example.com',
'secure' => true, // Only sent over HTTPS
'httponly' => true, // Prevents JavaScript access (XSS protection)
'samesite' => 'Lax' // Helps mitigate CSRF attacks
]);Legacy PHP Syntax (Pre-7.3)
If you are running an older version of PHP, you must define the
attributes as individual parameters. The httponly parameter
is the 7th argument:
// Parameters: name, value, expire, path, domain, secure, httponly
setcookie("user_session", "secure_token_value", time() + 3600, "/", "example.com", true, true);Method 2: Configuring PHP Session Cookies
PHP automatically generates a session cookie (usually named
PHPSESSID) when you call session_start().
Because session cookies are primary targets for hackers, you must ensure
they are configured as HttpOnly.
There are three ways to enforce this:
1. Via
php.ini (Recommended Global Method)
To secure session cookies across your entire server, modify your
global php.ini file:
session.cookie_httponly = On
session.cookie_secure = On ; Force cookies over HTTPS only2. Via .htaccess
(Apache Web Servers)
If you do not have access to php.ini, you can apply
these settings in your project’s .htaccess file:
php_value session.cookie_httponly 1
php_value session.cookie_secure 13. Within Your PHP Script at Runtime
If you must set these parameters dynamically, call
session_set_cookie_params() before
initiating the session with session_start():
// Configure session cookie parameters
session_set_cookie_params([
'lifetime' => 0, // Expire when browser closes
'path' => '/',
'domain' => 'example.com',
'secure' => true, // Only send over HTTPS
'httponly' => true, // Protect session ID from XSS
'samesite' => 'Lax'
]);
session_start();Alternatively, you can use ini_set() directly before
starting the session:
ini_set('session.cookie_httponly', 1);
ini_set('session.cookie_secure', 1);
session_start();