How do you set up HttpOnly cookies in PHP
Setting a cookie as HttpOnly is one of the most effective steps you can take to mitigate Cross-Site Scripting (XSS) vulnerabilities. When an XSS flaw exists in your application, an attacker can inject malicious JavaScript into the page. Without the HttpOnly flag, that script can access cookies sent with every request, effectively stealing session tokens and hijacking user accounts. By setting this flag, you instruct the browser to exclude the cookie from any client-side script access, rendering stolen tokens useless even if your application is compromised.
In standard PHP, you set this flag using the httponly parameter within the setcookie() function or by modifying the session configuration before calling session_start(). The syntax is straightforward, but understanding where and how to apply it is crucial for security hygiene.
If you are managing sessions via the default PHP session handler, you must configure this globally before any output is sent to the browser. You can do this by adding a specific option to the session configuration array. This approach ensures that every session cookie created thereafter inherits the HttpOnly attribute without needing to manually set it in every single request.
session_set_cookie_params([
'lifetime' => 0,
'path' => '/',
'domain' => $_SERVER['HTTP_HOST'],
'secure' => true, // Only set this on HTTPS
'httponly' => true,
'samesite' => 'Strict' // Recommended for CSRF protection
]);
session_start();
When you are not relying on the session mechanism or need to set a custom cookie for other purposes, the setcookie() function is required. The order of operations matters significantly here. You must call setcookie() before any HTML content, whitespace, or BOMs are echoed. If output has already started, the browser will ignore the header modification, and the cookie will be set without the HttpOnly flag by default.
if (isset($_GET['id'])) {
$user_id = $_GET['id'];
// Must happen before any echo or print statements
setcookie('user_pref', 'dark_mode', [
'expires' => time() + 31536000,
'path' => '/',
'domain' => $_SERVER['HTTP_HOST'],
'secure' => true, // Enforce HTTPS
'httponly' => true,
'samesite' => 'Lax'
]);
}
echo "Page content here...";
One common pitfall developers encounter is ignoring the secure flag when enabling HttpOnly. While HttpOnly prevents JavaScript from reading the cookie, it does not prevent network interception. If you are not serving your application over HTTPS, an attacker on a public Wi-Fi network could sniff the traffic and capture the session token regardless of the HttpOnly setting. Always enable the secure flag alongside httponly to ensure the cookie is only transmitted over encrypted connections.
Another consideration involves the samesite attribute. Modern browsers support SameSite attributes which help defend against Cross-Site Request Forgery (CSRF). While HttpOnly deals with data exfiltration via XSS, SameSite restricts when cookies are sent with cross-origin requests. Using both provides a layered defense strategy.
In larger applications built on frameworks like Laravel, these settings are often handled automatically or centralized in the service provider configuration. If you are maintaining a legacy PHP project or building a custom framework, ensuring these attributes are consistently applied across all cookie creation points is a non-negotiable requirement for modern web security standards.
For developers looking for robust session management solutions that abstract away these low-level details while enforcing best practices, resources like LaravelCompany offer insights into how enterprise-grade applications handle state securely.
