How to check whether the page is called from ‘https’ or ‘http’ in PHP ?
Last Updated :
17 Mar, 2021
The purpose of this article is to check whether the page is called from ‘HTTPS’ or ‘HTTP’, we can use the following two approaches.
Approach 1: Check if the connection is using SSL and if the value of $_SERVER[‘HTTPS’] is set, then we can say that the connection is secured and called from ‘HTTPS’. If the value is empty, this means the value is set to ‘0’ or ‘off’ then we can say that the connection is not secured and the page is called from ‘HTTP’.
$_SERVER is an array which contain all the information about request headers, paths, and script locations. It will have a ‘non-empty’ value if the request was sent through HTTPS and empty or ‘0’ if the request was sent through HTTP.
Syntax:
if (isset($_SERVER['HTTPS']))
{
// page is called from https
// Connection is secured
}
else
{
// page is called from http
// Connection is not secured
}
Flowchart:
Flowchart 1
Example:
PHP
<?php
if (isset( $_SERVER [ 'HTTPS' ])) {
echo "Page is called from HTTPS and connection is secured." ;
}
else
{
echo "Warning : Connection is not secured,Page is called from HTTP" ;
}
?>
|
Output:
Warning : Connection is not secured,Page is called from HTTP
Approach 2: A Problem with the earlier approach is that in some servers, the $_SERVER[‘HTTPS’] is undefined and this could lead to an error message while checking that the page is called from ‘HTTPS’ or from ‘HTTP’. So to overcome this, we have to check for server port number also, if the port number used is 443, the connection is made through ‘HTTPS’.
Pseudocode:
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
Syntax:
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
}
Flowchart:
Flowchart 2
Example:
PHP
<?php
if (isset( $_SERVER [ 'HTTPS' ]))
{
if ( $_SERVER [ 'HTTPS' ] == 'on' )
{
}
}
else if (isset( $_SERVER [ 'HTTPS' ]))
{
if ( $_SERVER [ 'SERVER_PORT' ] == 443)
{
echo "Connection is secured and page is called from HTTPS" ;
}
}
else
{
echo "Connection is not secured and page is called from HTTP" ;
}
?>
|
Output:
Connection is not secured and page is called from HTTP
Share your thoughts in the comments
Please Login to comment...