PHP

Setting Secure and HttpOnly Cookies in PHP

Learn to set secure and HttpOnly cookies in PHP, enhancing web application security by protecting sensitive session data from XSS and eavesdropping.

<?php
// Start a session if you're using session cookies
session_start();

// To explicitly set custom cookies securely:
$name = 'user_token';
$value = 'a_secret_token_value';
$expire = time() + (60 * 60 * 24 * 30); // 30 days from now
$path = '/';
$domain = ''; // Leave empty for current domain, or specify 'yourdomain.com'
$secure = true; // Only send over HTTPS connections
$httponly = true; // Not accessible via client-side JavaScript
$samesite = 'Lax'; // or 'Strict' or 'None'

setcookie($name, $value, [
    'expires' => $expire,
    'path' => $path,
    'domain' => $domain,
    'secure' => $secure,
    'httponly' => $httponly,
    'samesite' => $samesite
]);

echo "Secure cookie set.";
?>
How it works: This PHP snippet demonstrates how to set cookies with `Secure`, `HttpOnly`, and `SameSite` flags. The `Secure` flag ensures the cookie is only sent over HTTPS connections, protecting against eavesdropping. The `HttpOnly` flag prevents client-side JavaScript from accessing the cookie, mitigating XSS attacks. The `SameSite` flag protects against CSRF attacks by controlling when cookies are sent with cross-site requests. For session cookies, these settings are often configured in `php.ini`, but `setcookie()` allows explicit control for other custom cookies, which is critical for handling sensitive data.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs