📜  如何检查页面是从PHP中的“https”还是“http”调用的?

📅  最后修改于: 2022-05-13 01:56:26.306000             🧑  作者: Mango

如何检查页面是从PHP中的“https”还是“http”调用的?

本文的目的是检查页面是从“HTTPS”还是“HTTP”调用的,我们可以使用以下两种方法。

方法 1:检查连接是否使用 SSL,如果设置了$_SERVER['HTTPS']的值,那么我们可以说连接是安全的,并且是从 'HTTPS' 调用的。如果该值为空,这意味着该值设置为“0”或“关闭”,那么我们可以说连接不安全并且页面是从“HTTP”调用的。

$_SERVER是一个数组,其中包含有关请求标头、路径和脚本位置的所有信息。如果请求是通过 HTTPS 发送的,它将有一个“非空”值,如果请求是通过 HTTP 发送的,它将为空或“0”。

句法:

if (isset($_SERVER['HTTPS']))
{
 // page is called from https
 // Connection is secured
}
else
{
 // page is called from http
 // Connection is not secured
}

流程图:

流程图 1

例子:

PHP


PHP


输出:

Warning : Connection is not secured,Page is called from HTTP

方法 2:早期方法的一个问题是,在某些服务器中, $_SERVER['HTTPS']未定义,这可能导致在检查页面是从“HTTPS”还是从“HTTP”调用时出现错误消息。因此,为了克服这个问题,我们还必须检查服务器端口号,如果使用的端口号是 443,则连接是通过“HTTPS”建立的。

伪代码:

check if $_SERVER['HTTPS'] is set and $_SERVER['HTTPS']
is set to 'on' then Connection is Secured and through 
HTTPS request

OR 

if  $_SERVER['HTTPS'] is set and $_SERVER['SERVER_PORT'] 
is 443 ( https use 443 ) then Connection is secured 

else
    
Connection is not secured and made through HTTP request

句法:

if ((isset($_SERVER['HTTPS']) && 
        (($_SERVER['HTTPS'] == 'on'))) 
 || (isset($_SERVER['HTTPS']) && 
           $_SERVER['SERVER_PORT'] == 443))
  {
   Page is called through HTTPS 
 }
 else
  {
   Page is called through HTTPS
  }

流程图:

流程图 2

例子:

PHP


输出:

Connection is not secured and page is called from HTTP