Identify whether the current url is http or https

2019-02-21 01:36发布

问题:

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

回答1:

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

notice the on should be a string .



回答2:

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();


回答3:

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.



回答4:

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


回答5:

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