PHP

Implement HTTP Strict Transport Security (HSTS) Header in PHP

Enforce HTTPS connections for your website by sending the HSTS header. This PHP snippet ensures browsers only connect via HTTPS, preventing downgrade attacks.

<?php
/**
 * Sets the HSTS header to ensure all future connections are via HTTPS.
 *
 * @param int $maxAge The time in seconds that the browser should remember
 *                    that a site is only to be accessed using HTTPS.
 *                    Default: 31536000 seconds (1 year).
 * @param bool $includeSubDomains Optional. If true, this rule applies
 *                                to all of the site's subdomains as well.
 * @param bool $preload Optional. If true, indicates intent to be included
 *                      in the HSTS preload list built into major browsers.
 *                      Requires prior submission to the official preload list.
 */
function setHSTSHeader(int $maxAge = 31536000, bool $includeSubDomains = true, bool $preload = false): void
{
    // Only set HSTS header if the connection is already secure (HTTPS).
    // Sending HSTS over HTTP is a security risk.
    if (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') {
        $hstsHeader = "Strict-Transport-Security: max-age={$maxAge}";
        if ($includeSubDomains) {
            $hstsHeader .= "; includeSubDomains";
        }
        if ($preload) {
            $hstsHeader .= "; preload";
        }
        header($hstsHeader);
    }
}

// --- Usage Example ---
// Call this function early in your application's bootstrap,
// before any content is sent to the browser.
setHSTSHeader();

// Optionally, specify a shorter max-age during development or for testing
// setHSTSHeader(maxAge: 300, includeSubDomains: false); // 5 minutes, no subdomains

// Your application logic continues here.
echo "HSTS header potentially set (check browser network tab if on HTTPS).
";
?>
How it works: This PHP snippet demonstrates how to implement the HTTP Strict Transport Security (HSTS) header. When sent over an HTTPS connection, the `Strict-Transport-Security` header instructs browsers to always connect to your domain via HTTPS for a specified duration (`max-age`). This helps prevent downgrade attacks (where attackers try to force a less secure HTTP connection) and protects against cookie hijacking, significantly enhancing website security.

Need help integrating this into your project?

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

Hire DigitalCodeLabs