Identify whether the current url is http or https

2019-02-21 01:43发布

I have a website in Zend framework. Here I want to identify whether the current URL contains HTTPS or HTTP? I have used the following code

if($_SERVER['HTTPS']==on){ echo "something";}else{ echo "something other";}

But the result is not correct. Is there is any other way to identify this? Also I have one more question. How to get complete current url (including HTTP/HTTPS) using php?

Please help me

Thanks in advance

5条回答
叛逆
2楼-- · 2019-02-21 01:51

You could use methods that are already defined in Zend Framework instead of explicitly using $_SERVER superglobals.

To determine if the connection is HTTP or HTTPS (this code should go into your controller):

if ( $this->getRequest()->isSecure() ) { echo 'https'; } else { echo 'http'; }

To get complete current url:

$this->getRequest()->getScheme() . '://' . $this->getRequest()->getHttpHost() . $this->getRequest()->getRequestUri();
查看更多
Deceive 欺骗
3楼-- · 2019-02-21 01:59

This will both check if you're using https or http and output the current url.

$https = ((!empty($_SERVER['HTTPS'])) && ($_SERVER['HTTPS'] != 'off')) ? true : false;

if($https) {
    $url = "https://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
} else {
    $url = "http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
}
查看更多
▲ chillily
4楼-- · 2019-02-21 02:00
if(isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == "on") { 
    echo "something";
} else { 
    echo "something other";
}

notice the on should be a string .

查看更多
等我变得足够好
5楼-- · 2019-02-21 02:04

The better way to check is

if (isset($_SERVER['HTTPS']) && $_SEREVER['HTTPS'] != 'off')
{
  //connection is secure do something
}
else
{
  //http is used
}

As stated in manual

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

Note: Note that when using ISAPI with IIS, the value will be off if the

request was not made through the HTTPS protocol.

查看更多
趁早两清
6楼-- · 2019-02-21 02:14

you need to fix check it should be

if ($_SERVER['HTTPS'] == 'on')

or try following function

if(detect_ssl()){ echo "something";}else{ echo "something other";}

function detect_ssl() {
return ($_SERVER['HTTPS'] == 'on' || $_SERVER['HTTPS'] == 1 || $_SERVER['SERVER_PORT'] == 443)
}
查看更多
登录 后发表回答