Implementing HTTP Strict Transport Security (HSTS) in PHP
Owner: SnippetBot
Created: 2026-11-03 00:00:48
Size: 2.40 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<?php
// Function to check if the current request is HTTPS
function isHttps() {
if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') {
return true;
}
// For some proxy configurations
if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https') {
return true;
}
return false;
}
// Ensure the site is accessed via HTTPS before sending HSTS header
if (!isHttps()) {
// Redirect to HTTPS if not already on it
header("Location: https://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"], true, 301);
exit();
}
// HTTP Strict Transport Security (HSTS) Header
// Tells browsers to only connect to this site using HTTPS for a specified duration.
// max-age: The time (in seconds) that the browser should remember that a site is only to be accessed using HTTPS.
// includeSubDomains: Optional. If this optional parameter is specified, this rule applies to all of the site's subdomains as well.
// preload: Optional. Not part of the RFC, but often used to pre-load sites into browser HSTS lists. Requires prior submission.
header("Strict-Transport-Security: max-age=31536000; includeSubDomains; preload");
// X-Frame-Options: Prevents clickjacking by controlling whether your content can be embedded in iframes.
// SAMEORIGIN: The page can only be displayed in a frame on the same origin as the page itself.
// DENY: The page cannot be displayed in a frame, regardless of the site attempting to do so.
header("X-Frame-Options: SAMEORIGIN");
// X-Content-Type-Options: Prevents browsers from MIME-sniffing a response away from the declared Content-Type.
// Helps mitigate drive-by download attacks.
header("X-Content-Type-Options: nosniff");
// Referrer-Policy: Controls how much referrer information is included with requests.
// strict-origin-when-cross-origin: Sends origin for same-origin and cross-origin secure requests, but no referrer for insecure.
header("Referrer-Policy: strict-origin-when-cross-origin");
// X-XSS-Protection: This header was for older browsers with built-in XSS filters.
// Modern browsers mostly deprecate it in favor of CSP, but it can still be included for legacy support.
// header("X-XSS-Protection: 1; mode=block"); // Often recommended to disable if CSP is strong.
// Your application logic starts here
echo "<h1>Welcome to a secure page!</h1>";
echo "<p>This page is served with HSTS and other security headers.</p>";
// ...
?>