I've seen many tutorials online that says you need to check $_SERVER['HTTPS']
if the server is connection is secured with HTTPS. My problem is that on some of the servers I use, $_SERVER['HTTPS']
is an undefined variable that results in an error. Is there another variable I can check that should always be defined?
Just to be clear, I am currently using this code to resolve if it is an HTTPS connection:
if(isset($_SERVER['HTTPS'])) {
if ($_SERVER['HTTPS'] == "on") {
$secure_connection = true;
}
}
This is how i find solve this
The REAL answer: ready for copy-paste into a [config] script
$pv_URIprotocol
is now correct and ready to be used; example$site=$pv_URIprotocol.$_SERVER["SERVER_NAME"]
. Naturally, the string could be replaced with TRUE and FALSE also. PV stands for PortalPress Variable as it is a direct copy-paste which will always work. This piece can be used in a production script.You could check
$_SERVER['SERVER_PORT']
as SSL normally runs on port 443, but this is not foolproof.Here is a re-usable function that I have been using for a while. HTH.
Note: The value of HTTPS_PORT (which is a custom constant in my code) may vary on your envrionment, for example it may be 443 or 81.
My solution (because the standard conditions [$_SERVER['HTTPS'] == 'on'] do not work on servers behind a load balancer) is:
HTTP_X_FORWARDED_PROTO: a de facto standard for identifying the originating protocol of an HTTP request, since a reverse proxy (load balancer) may communicate with a web server using HTTP even if the request to the reverse proxy is HTTPS http://en.wikipedia.org/wiki/List_of_HTTP_header_fields#Common_non-standard_request_headers
I have occasion to go a step further and determine if the site I'm connecting to is SSL capable (one project asks the user for their URL and we need to verify they have installed our API pack on a http or https site).
Here's the function I use - basically, just call the URL via cURL to see if https works!
This is the most reliable way I have found to not only find out IF you are using https (as the question asks), but if you COULD (or even SHOULD) be using https.
NOTE: it is possible (though not really likely...) that a site could have different http and https pages (so if you are told to use http, maybe you don't need to change..) The vast majority of sites are the same, and probably should reroute you themselves, but this additional check has its use (certainly as I said, in the project where the user inputs their site info and you want to make sure from the server side)