213

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;
    }
}
Quill
  • 2,729
  • 1
  • 33
  • 44
Tyler Carter
  • 60,743
  • 20
  • 130
  • 150
  • By any chances, those servers where $_SERVER['HTTPS'] is undefined are running on HTTPS? – Freddy Jul 23 '09 at 23:50
  • Actually, one of them is my home WAMP server. And I don't believe it is running on HTTPS. – Tyler Carter Jul 23 '09 at 23:51
  • @TylerCarter, An [alternative method is to use `Secure` cookies.](http://stackoverflow.com/a/28891745/632951) Be careful with the gotchas though. – Pacerier Mar 06 '15 at 03:15

28 Answers28

312

This should always work even when $_SERVER['HTTPS'] is undefined:

function isSecure() {
  return
    (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')
    || $_SERVER['SERVER_PORT'] == 443;
}

The code is compatible with IIS.

From the PHP.net documentation and user comments :

  1. Set to a non-empty value if the script was queried through the HTTPS protocol.

  2. Note that when using ISAPI with IIS, the value will be "off" if the request was not made through the HTTPS protocol. (Same behaviour has been reported for IIS7 running PHP as a Fast-CGI application).

Also, Apache 1.x servers (and broken installations) might not have $_SERVER['HTTPS'] defined even if connecting securely. Although not guaranteed, connections on port 443 are, by convention, likely using secure sockets, hence the additional port check.

Additional note: if there is a load balancer between the client and your server, this code doesn't test the connection between the client and the load balancer, but the connection between the load balancer and your server. To test the former connection, you would have to test using the HTTP_X_FORWARDED_PROTO header, but it's much more complex to do; see latest comments below this answer.

Gras Double
  • 15,901
  • 8
  • 56
  • 54
  • this is more than enough i my case, +1 – Alex K Aug 23 '13 at 14:56
  • 60
    Nb: port 443 does not guarantee connection is encrypted – ErichBSchulz Feb 01 '14 at 01:35
  • http://php.net/manual/en/function.getservbyname.php can check `https` port via `getservbyname("https", "tcp")`. – David Rodrigues Jul 17 '14 at 21:22
  • 2
    @DavidRodrigues That isn't true. You can use HTTP/HTTPS over whatever port you want. `getservbyname()` is only a reference, not reality, and does not in any way guarantee that HTTPS is running over port 443. – Brad Dec 04 '14 at 17:12
  • 1
    I had a small problem with `$_SERVER['SERVER_PORT'] !== 443` I had to cast `$_SERVER['SERVER_PORT]` to an integer like so: `intval($_SERVER['SERVER_PORT]) !== 443` – m.e.conroy Jun 12 '15 at 15:34
  • 1
    1) The server port check is an extra for sheetty servers, best to remove it if it is not needed. 2) Notice it's a loose comparison in my answer ;) – Gras Double Jun 13 '15 at 00:02
  • 1
    One more small issue I ran into today. The server was returning 'OFF' not 'off' - `strtolower($_SERVER['HTTPS']) !== 'off'` did the trick. – jhummel Apr 14 '16 at 18:47
  • @jhummel Interesting, could you please tell what is the server? – Gras Double Apr 15 '16 at 10:17
  • @GrasDouble It would be a pretty rare occurrence. It was a node connect server running a php gateway, used for development. – jhummel Apr 17 '16 at 18:47
  • Nope. Got a shared hosting account where the https:// version is served over port 80 AND there is no $_SERVER["HTTPS"]. Checking the port will *not* always work. – Peter Kionga-Kamau Mar 27 '17 at 18:05
  • UPDATE: this turns out to be resulting from a flexible ssl in the cloudflare settings. So if you're seeing mixed content errors and you're behind a service like Cloudflare, check that you're using ssl for communication between Cloudflare and your server – Peter Kionga-Kamau Mar 27 '17 at 18:12
  • Please update the solution including HTTP_X_FORWARDED_PROTO – opengrid Sep 23 '19 at 11:50
  • 1
    Implementing `HTTP_X_FORWARDED_PROTO` is significantly more complicated than it seems, because for security reasons you have to check if the client (expectedly the load balancer) is in a whitelist. See in [Symfony's Request](https://github.com/symfony/symfony/blob/master/src/Symfony/Component/HttpFoundation/Request.php) the method `isSecure` (and the methods `isFromTrustedProxy` and `getTrustedValues` that it calls). – Gras Double Sep 23 '19 at 15:26
135

My solution (because the standard conditions [$_SERVER['HTTPS'] == 'on'] do not work on servers behind a load balancer) is:

$isSecure = false;
if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {
    $isSecure = true;
}
elseif (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' || !empty($_SERVER['HTTP_X_FORWARDED_SSL']) && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on') {
    $isSecure = true;
}
$REQUEST_PROTOCOL = $isSecure ? 'https' : 'http';

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

temuraru
  • 1,538
  • 1
  • 10
  • 7
  • 5
    This is the solution if you use the varnish reverse proxy. – Reto Zahner May 22 '13 at 14:48
  • 2
    My issue got resolved with this solution. (PHP - AWS Elastic beanstalk) – user4826347 Mar 17 '16 at 20:45
  • This is the solution if you use load balancers. – Abhishek Saini Jul 13 '16 at 16:18
  • What type of file are you sticking this in? I am assuming this is not in the .htaccess file? – Jordan Aug 22 '16 at 15:52
  • 6
    This also work for the free HTTPS provided by CloudFlare. – AnthonyVO Jan 28 '17 at 14:30
  • This is the correct solution. I have tested with the flywheel server varnish reverse proxy – Kuppuraj Jul 13 '18 at 11:48
  • @temuraru this helped me a bunch! I have tested a LOT of other issues, and somehow those did not work with my server when using CloudFlare. But this did the trick. Thank you for sharing. – Preben May 14 '19 at 09:53
  • 2
    Worth considering, from a security point of view, the `HTTP_X_FORWARDED_PROTO` proxy workaround might allow a smart attacker to avoid SSL by saying they were using SSL when they weren't. – Brian C Dec 26 '19 at 06:20
  • If you have to fallback to forwarded information then you should also check that the sender is a whitelisted IP (cloudfare/incapsula/etc ranges). X headers are easily spoofed... – zanderwar Jan 12 '21 at 00:53
  • 1
    This should be marked as the correct answer. – Shady Medic May 04 '21 at 07:54
  • This worked for my Cloudways-hosted site. They give you a temporary hostname (e.g. https://wordpress-{unique_id}.cloudwaysapps.com/) to access your site before going LIVE. The REQUEST_SCHEME and SERVER_PORT incorrectly reflects that requests are http-based. HTTP_X_FORWARDED_PROTO meanwhile shows correctly that they're https-based. – alds Dec 22 '21 at 20:40
84

Chacha, per the PHP documentation: "Set to a non-empty value if the script was queried through the HTTPS protocol." So your if statement there will return false in many cases where HTTPS is indeed on. You'll want to verify that $_SERVER['HTTPS'] exists and is non-empty. In cases where HTTPS is not set correctly for a given server, you can try checking if $_SERVER['SERVER_PORT'] == 443.

But note that some servers will also set $_SERVER['HTTPS'] to a non-empty value, so be sure to check this variable also.

Reference: Documentation for $_SERVER and $HTTP_SERVER_VARS [deprecated]

Quill
  • 2,729
  • 1
  • 33
  • 44
hobodave
  • 28,925
  • 4
  • 72
  • 77
  • 13
    use $_SERVER['SERVER_PORT'] can be tricky... for example ispconfig uses port 81 as secure port so lets say that 443 is the "default" port for ssl. – Gabriel Sosa Jul 24 '09 at 01:58
  • @Gabriel Sosa - True, but caveats can be addressed on a case by case basis. @hobodave's answer will work for most. – Tim Post May 21 '10 at 23:30
  • 1
    Note that this will not work behind a reverse proxy. One might consider to check `HTTP_X_FORWARDED_PROTO` or `HTTP_X_FORWARDED_SSL` as well. – paolo Dec 14 '17 at 09:45
  • 1
    I agree with that last resort should be port number, so here is my check: `(((isset($_SERVER['HTTPS'])) && (strtolower($_SERVER['HTTPS']) == 'on')) || ((isset($_SERVER['HTTP_X_FORWARDED_PROTO'])) && (strtolower($_SERVER['HTTP_X_FORWARDED_PROTO']) == 'https')))` which does not include port check at all. Feel free to add. :-) – Roland Apr 11 '18 at 21:32
  • @paolo behind a reverse proxy `SetEnvIf X-Forwarded-SSL on HTTPS=on` will do the trick. But this will not work with `REQUEST_SCHEME` as a result in php seems better to use `$_SERVER['HTTPS']` – Antony Gibbs Nov 29 '18 at 02:12
17

This also works when $_SERVER['HTTPS'] is undefined

if( (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') || $_SERVER['SERVER_PORT'] == 443 ){
    //enable secure connection
}
Thamaraiselvam
  • 6,961
  • 8
  • 45
  • 71
17

Making my own function from reading all previous posts:

public static function isHttps()
{
    if (array_key_exists("HTTPS", $_SERVER) && 'on' === $_SERVER["HTTPS"]) {
        return true;
    }
    if (array_key_exists("SERVER_PORT", $_SERVER) && 443 === (int)$_SERVER["SERVER_PORT"]) {
        return true;
    }
    if (array_key_exists("HTTP_X_FORWARDED_SSL", $_SERVER) && 'on' === $_SERVER["HTTP_X_FORWARDED_SSL"]) {
        return true;
    }
    if (array_key_exists("HTTP_X_FORWARDED_PROTO", $_SERVER) && 'https' === $_SERVER["HTTP_X_FORWARDED_PROTO"]) {
        return true;
    }
    return false;
}
ling
  • 9,545
  • 4
  • 52
  • 49
11

I have just had an issue where I was running the server using Apache mod_ssl, yet a phpinfo() and a var_dump( $_SERVER ) showed that PHP still thinks I'm on port 80.

Here is my workaround for anyone with the same issue....

<VirtualHost *:443>
  SetEnv HTTPS on
  DocumentRoot /var/www/vhost/scratch/content
  ServerName scratch.example.com
</VirtualHost>

The line worth noting is the SetEnv line. With this in place and after a restart, you should have the HTTPS environment variable you always dreamt of

thomas-peter
  • 7,738
  • 6
  • 43
  • 58
8

If your are using Apache you may always count on

$_SERVER["REQUEST_SCHEME"]

to verify the scheme of the URL requested. But, as mentioned in other answers, it is prudent to verify other parameters before assuming SSL is really being used.

Ed de Almeida
  • 3,675
  • 4
  • 25
  • 57
5

The REAL answer: ready for copy-paste into a [config] script

/* configuration settings; X=edit may 10th '11 */
$pv_sslport=443; /* for it might be different, as also Gabriel Sosa stated */
$pv_serverport=80; /* X */
$pv_servername="mysite.com"; /* X */

/* X appended after correction by Michael Kopinsky */
if(!isset($_SERVER["SERVER_NAME"]) || !$_SERVER["SERVER_NAME"]) {
    if(!isset($_ENV["SERVER_NAME"])) {
        getenv("SERVER_NAME");
        // Set to env server_name
        $_SERVER["SERVER_NAME"]=$_ENV["SERVER_NAME"];
    }
}
if(!$_SERVER["SERVER_NAME"]) (
    /* X server name still empty? ... you might set $_SERVER["SERVER_NAME"]=$pv_servername; */
}

if(!isset($_SERVER["SERVER_PORT"]) || !$_SERVER["SERVER_PORT"]) {
    if(!isset($_ENV["SERVER_PORT"])) {
        getenv("SERVER_PORT");
        $_SERVER["SERVER_PORT"]=$_ENV["SERVER_PORT"];
    }
}
if(!$_SERVER["SERVER_PORT"]) (
    /* X server port still empty? ... you might set $_SERVER["SERVER_PORT"]=$pv_serverport; */
}

$pv_URIprotocol = isset($_SERVER["HTTPS"]) ? (($_SERVER["HTTPS"]==="on" || $_SERVER["HTTPS"]===1 || $_SERVER["SERVER_PORT"]===$pv_sslport) ? "https://" : "http://") :  (($_SERVER["SERVER_PORT"]===$pv_sslport) ? "https://" : "http://");

$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.

helvete
  • 2,455
  • 13
  • 33
  • 37
5

I know this answer is late, but I combined a bunch of answers and made a simple function that works for all use cases.

Try this:

function is_ssl(){
if(isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO']=="https"){ return true; }
elseif(isset($_SERVER['HTTPS'])){ return true; }
elseif($_SERVER['SERVER_PORT'] == 443){ return true; }
else{ return false; }
}

Then just use if, for example:

if(is_ssl()){
// WHAT TO DO IF IT IS SSL / HTTPS
}else{
// WHAT TO DO IF IT IS NOT SSL / HTTPS
}

This code works with Cloudflare, shared hosting providers, etc.

Enjoy.

Nemosciri
  • 59
  • 1
  • 1
3

The only reliable method is the one described by Igor M.

$pv_URIprotocol = isset($_SERVER["HTTPS"]) ? (($_SERVER["HTTPS"]==="on" || $_SERVER["HTTPS"]===1 || $_SERVER["SERVER_PORT"]===$pv_sslport) ? "https://" : "http://") :  (($_SERVER["SERVER_PORT"]===$pv_sslport) ? "https://" : "http://");

Consider following: You are using nginx with fastcgi, by default(debian, ubuntu) fastgi_params contain directive:

fastcgi_param HTTPS $https;

if you are NOT using SSL, it gets translated as empty value, not 'off', not 0 and you are doomed.

http://unpec.blogspot.cz/2013/01/nette-nginx-php-fpm-redirect.html

Galvani
  • 239
  • 2
  • 9
3

I find these params acceptable as well and more then likely don't have false positives when switching web servers.

  1. $_SERVER['HTTPS_KEYSIZE']
  2. $_SERVER['HTTPS_SECRETKEYSIZE']
  3. $_SERVER['HTTPS_SERVER_ISSUER']
  4. $_SERVER['HTTPS_SERVER_SUBJECT']

    if($_SERVER['HTTPS_KEYSIZE'] != NULL){/*do foobar*/}
    
Werezywolf
  • 31
  • 1
3

Shortest way I am using:

$secure_connection = !empty($_SERVER['HTTPS']);

If if https is used, then $secure_connection is true.

Markus Zeller
  • 8,516
  • 2
  • 29
  • 35
3

I don't think that adding a port is good idea - specially when you got many servers with different builds. that just adds one more thing to remember to change. looking at doc's I think the last line of kaisers is quite good, so that:

if(!empty($_SERVER["HTTPS"]))
  if($_SERVER["HTTPS"]!=="off")
    return 1; //https
  else
    return 0; //http
else
  return 0; //http

seems like perfectly enough.

Toon Krijthe
  • 52,876
  • 38
  • 145
  • 202
sp3c1
  • 31
  • 1
2

You could check $_SERVER['SERVER_PORT'] as SSL normally runs on port 443, but this is not foolproof.

Paolo Bergantino
  • 480,997
  • 81
  • 517
  • 436
pix0r
  • 31,139
  • 18
  • 86
  • 102
2

What do you think of this?

if (isset($_SERVER['HTTPS']) && !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off')
    $scheme = 'https';
else
    $scheme = 'http';
toni rmc
  • 848
  • 2
  • 10
  • 25
  • Yes there is. If you rely only on empty() PHP will exit with error if there is no 'HTTPS' index. – toni rmc Jan 14 '16 at 03:12
  • 3
    "empty() is essentially the concise equivalent to !isset($var) || $var == false" - http://php.net/manual/en/function.empty.php – John Magnolia Jan 14 '16 at 07:48
  • 2
    You are right. Funny I missed that one. I always thought empty() will fail if variable does not exist. – toni rmc Jan 16 '16 at 04:56
2

On my server (Ubuntu 14.10, Apache 2.4, php 5.5) variable $_SERVER['HTTPS'] is not set when php script is loaded via https. I don't know what is wrong. But following lines in .htaccess file fix this problem:

RewriteEngine on

RewriteCond %{HTTPS} =on [NC] 
RewriteRule .* - [E=HTTPS:on,NE]
Karry
  • 381
  • 3
  • 4
1

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.

/**
 * Determine if this is a secure HTTPS connection
 * 
 * @return  bool    True if it is a secure HTTPS connection, otherwise false.
 */
function isSSL()
{
    if (isset($_SERVER['HTTPS'])) {
        if ($_SERVER['HTTPS'] == 1) {
            return true;
        } elseif ($_SERVER['HTTPS'] == 'on') {
            return true;
        }
    } elseif ($_SERVER['SERVER_PORT'] == HTTPS_PORT) {
        return true;
    }

    return false;
}
crmpicco
  • 16,605
  • 26
  • 134
  • 210
1

just for interest, chrome canary at the moment sends

HTTPS : 1

to the server, and depending on how the server is configured can mean that you get back the following

HTTPS : 1, on

This broke our application because we were testing if on, which it obviously isn't. At the moment, only chrome canary seems to do this, but its worth noting that things from canary generally land in "normal" chrome a short while later.

John Smith
  • 1,812
  • 1
  • 16
  • 17
1

If You use nginx as loadbalancing system check $_SERVER['HTTP_HTTPS'] == 1 other checks will be fail for ssl.

basis
  • 158
  • 2
  • 8
1
$secure_connection = ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') || (!empty($_SERVER['HTTP_HTTPS']) && $_SERVER['HTTP_HTTPS'] != 'off') || $_SERVER['REQUEST_SCHEME'] == 'https' || $_SERVER['SERVER_PORT'] == 443) ? true : false;

Code is checking anything possible and works also on IIS web server. Chrome since v44 do not set header HTTP: 1 so checking HTTP_HTTPS is OK. If this code does not match https it means your webserver or proxy server is poorly configured. Apache itself sets HTTPS flag correctly but there can be problem when you use proxy (e.g. nginx). You must set some header in nginx https virtual host

proxy_set_header   X-HTTPS 1;

and use some Apache module to set HTTPS flag correctly by looking for X-HTTPS from proxy. Search for mod_fakessl, mod_rpaf, etc.

mikep
  • 5,880
  • 2
  • 30
  • 37
1

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!

function hasSSL($url) 
{
    // take the URL down to the domain name
    $domain = parse_url($url, PHP_URL_HOST);
    $ch = curl_init('https://' . $domain);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'HEAD'); //its a  HEAD
    curl_setopt($ch, CURLOPT_NOBODY, true);          // no body
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);  // in case of redirects
    curl_setopt($ch, CURLOPT_VERBOSE, 0); //turn on if debugging
    curl_setopt($ch, CURLOPT_HEADER, 1);     //head only wanted
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);    // we dont want to wait forever
    curl_exec($ch);
    $header = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    if ($header === 200) {
        return true;
    }
    return false;
}

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)

Apps-n-Add-Ons
  • 2,026
  • 1
  • 17
  • 28
0

If you are using Incapsula's load balancer you'll need to use an IRule to generate a custom header for your server. I created an HTTP_X_FORWARDED_PROTO header that is equal to either "http" if the port is set to 80 and "https" if it is equal to 443.

Nadav
  • 1,055
  • 1
  • 10
  • 23
0

I would add a global filter to ensure everything I am checking is correct;

function isSSL() {

    $https = filter_input(INPUT_SERVER, 'HTTPS');
    $port = filter_input(INPUT_SERVER, 'SERVER_PORT');
    if ($https) {

        if ($https == 1) {
            return true;
        } elseif ($https == 'on') {
            return true;
        }
    } elseif ($port == '443') {
        return true;
    }

    return false;
}
codediesel
  • 43
  • 6
0

This is how i find solve this

$https = !empty($_SERVER['HTTPS']) && strcasecmp($_SERVER['HTTPS'], 'on') === 0 ||
        !empty($_SERVER['HTTP_X_FORWARDED_PROTO']) &&
            strcasecmp($_SERVER['HTTP_X_FORWARDED_PROTO'], 'https') === 0;

return ($https) ? 'https://' : 'http://';
0

I used the main suggestion here and got annoyed at the "PHP Notice" in the logs when HTTPS was not set. You can avoid it by using the null-coalescing operator "??":

if( ($_SERVER['HTTPS'] ?? 'off') == 'off' ) {
    // redirect
}

(Note: not available prior to php v7)

garafajon
  • 1,278
  • 13
  • 15
0

If you don't have control of the web server & don't know which variables have been set, upload this php to find out:

<?php
echo "<br>1 ".$_SERVER["HTTPS"];
echo "<br>2 ".$_SERVER["SERVER_PORT"];
echo "<br>3 ".$_SERVER["HTTP_X_FORWARDED_PROTO"];
echo "<br>4 ".$_SERVER["HTTP_X_FORWARDED_SSL"];
echo "<br>5 ".$_SERVER["HTTP_HTTPS"];
echo "<br>6 ".$_SERVER["REQUEST_SCHEME"];
?>

<html>
<body>
<br>
Just cruising
</body>
</html>
Zimba
  • 2,854
  • 18
  • 26
0

I use cloudflare for my systems. I had to access the $_SERVER['HTTP_CF_VISITOR'] value.

$isSsl = false; 
    if (isset($_SERVER['HTTP_CF_VISITOR'])) {
        $cfDecode = json_decode($_SERVER['HTTP_CF_VISITOR']);
        if (!empty($cfDecode) && !empty($cfDecode->scheme) && $cfDecode->scheme == 'https') {
            $isSsl = true;
        }
    }
var_dump($isSsl);
Rotimi
  • 4,783
  • 4
  • 18
  • 27
-8

As per hobodave's post: "Set to a non-empty value if the script was queried through the HTTPS protocol."

if (!empty($_SERVER['HTTPS']))
{
    $secure_connection = true;
}
user128026
  • 651
  • 4
  • 7