---
title: Set Secure Flag On Session Cookies
impact: HIGH
impactDescription: prevents session cookies from being transmitted over unencrypted HTTP connections
tags: cookies, secure, https, session, security, php
---

## Set Secure Flag On Session Cookies

The `Secure` attribute ensures that cookies are only transmitted over encrypted (HTTPS) connections. Without this flag, a session cookie could be sent over a plain HTTP connection (e.g., if a user manually changes the URL to `http://`), exposing it to network eavesdroppers.

**Incorrect (no Secure flag):**

```php
// Insecure: cookie will be sent over HTTP
setcookie("session_id", $token);

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

**Correct (Secure flag set):**

```php
// 1. Using setcookie (PHP 7.3+)
setcookie("session_id", $token, [
    'expires' => time() + 3600,
    'path' => '/',
    'domain' => 'example.com',
    'secure' => true,     // Enforces HTTPS
    'httponly' => true,
    'samesite' => 'Strict',
]);

// 2. Setting it for the entire session (at the start of script)
session_set_cookie_params([
    'lifetime' => 0,
    'path' => '/',
    'domain' => '',
    'secure' => true,
    'httponly' => true,
    'samesite' => 'Lax'
]);
session_start();

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

**Best Practices:**
- Always set `secure => true` in production environments.
- Use HSTS (`Strict-Transport-Security`) headers to force the browser to use HTTPS for all future requests.
- If your application is served via a load balancer, ensure the `X-Forwarded-Proto` header is respected so PHP correctly identifies the HTTPS connection.

**Tools:** PHP Internal configuration, OWASP ZAP, Burp Suite, SonarQube
