【问题标题】:Identify whether the current url is http or https in a project识别项目中当前url是http还是https
【发布时间】:2011-02-16 07:26:15
【问题描述】:

我在 Zend 框架中有一个网站。这里我要识别当前的URL是包含HTTPS还是HTTP?我使用了以下代码

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

但结果不正确。有没有其他方法可以识别这个? 我还有一个问题。 如何使用 php 获取完整的当前 url(包括 HTTP/HTTPS)?

请帮帮我

提前致谢

【问题讨论】:

    标签: php zend-framework ssl https


    【解决方案1】:
    if(isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == "on") { 
        echo "something";
    } else { 
        echo "something other";
    }
    

    注意on 应该是一个字符串。

    【讨论】:

    • 我一直在寻找相同的解决方案一段时间,但在我的服务器上我得到未定义的索引:HTTPS,即使我在 https 上冲浪
    • 看下面的答案,检查端口
    • 您应该在访问之前检查$_SERVER['HTTPS'] 是否已设置。
    • @Tom 感谢您指出这一点,但我相信我们应该让用户做他们的功课,并只给他们指导线(如果可能的话),也可以应用于其他问题。
    【解决方案2】:

    您可以使用 Zend Framework 中已经定义的方法,而不是显式使用 $_SERVER 超全局变量。

    要确定连接是 HTTP 还是 HTTPS(此代码应该进入您的控制器):

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

    获取完整的当前网址:

    $this->getRequest()->getScheme() . '://' . $this->getRequest()->getHttpHost() . $this->getRequest()->getRequestUri();
    

    【讨论】:

      【解决方案3】:

      更好的检查方法是

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

      如手册所述

      如果脚本设置为非空值 是通过 HTTPS 查询的 协议。

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

      请求不是通过 HTTPS 发出的 协议。

      【讨论】:

        【解决方案4】:

        你需要修复检查它应该是

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

        或尝试以下功能

        if(detect_ssl()){ echo "something";}else{ echo "something other";}
        
        function detect_ssl() {
        return ($_SERVER['HTTPS'] == 'on' || $_SERVER['HTTPS'] == 1 || $_SERVER['SERVER_PORT'] == 443)
        }
        

        【讨论】:

          【解决方案5】:

          这将检查您是否使用 https 或 http 并输出当前 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'];
          }
          

          【讨论】:

            猜你喜欢
            • 2015-08-05
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2010-12-27
            • 2014-01-07
            • 2011-03-22
            • 1970-01-01
            相关资源
            最近更新 更多