How to find out if you're using HTTPS without

2019-01-01 03:24发布

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;
    }
}

标签: php https
24条回答
冷夜・残月
2楼-- · 2019-01-01 04:01

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

查看更多
有味是清欢
3楼-- · 2019-01-01 04:05

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;
}
查看更多
怪性笑人.
4楼-- · 2019-01-01 04:07

Shortest way I am using:

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

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

查看更多
闭嘴吧你
5楼-- · 2019-01-01 04:08

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

if( (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') || $_SERVER['SERVER_PORT'] == 443 ){
    //enable secure connection
}
查看更多
还给你的自由
6楼-- · 2019-01-01 04:08

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;
}
查看更多
其实,你不懂
7楼-- · 2019-01-01 04:09

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]

查看更多
登录 后发表回答