Is there a problem with issuing a HSTS header in PHP?
HSTS is enabled by returning the strict-transport-security
header from a HTTPS response - the browser does not care whether this is set in PHP, by the server, or by a load balancer - as long as it receives a valid header over HTTPS then HSTS will be enabled.
You should be OK only returning this header from a single page for testing too. RFC 6797 states
If a UA receives HTTP responses from a Known HSTS Host over a secure channel but the responses are missing the STS header field, the UA MUST continue to treat the host as a Known HSTS Host until the max-age value for the knowledge of that Known HSTS Host is reached.
so your other responses without the header will not cancel HSTS for your site.
Setting max-age=0
is also the correct way to cancel HSTS for your site (per receiving user agent). The only thing I've spotted which is non-standard the way you are doing is that you are sending the header over HTTP also - although this would be ignored by a compliant user agent it is invalid so I would make sure to only transmit this when the connection is secure (best to stick to standards as close as possible I find).
You can check whether to emit the header with the following code that will check that the page has been accessed via HTTPS:
<?php
function isSSL(){
if($_SERVER['https'] == 1) /* Apache */ {
return TRUE;
} elseif ($_SERVER['https'] == 'on') /* IIS */ {
return TRUE;
} elseif ($_SERVER['SERVER_PORT'] == 443) /* others */ {
return TRUE;
} else {
return FALSE; /* just using http */
}
}
?>