PHP Check HTTPS or HTTP: Simple Guide for Web Developers

By Shahnail Khan Last updated : December 19, 2023

Problem statement

Write a PHP script, to check whether the page is called from 'https' or 'http'.

Prerequisites

To understand this solution better, you should have the basic knowledge of the following PHP topics:

Displaying whether the page is accessed via HTTPS or HTTP using PHP

We use the $_SERVER superglobal variable in PHP to know whether the page is called from HTTPS or HTTP.

The $_SERVER is an array containing server-related information, such as headers, paths, and script locations. This information is entered by a web server and can be accessed through the $_SERVER variable. The general syntax for accessing elements within the $_SERVER superglobal array in PHP is:

$_SERVER['key'];

For this problem, the value of the key is HTTPS, which typically contains information about the secure connection.

In PHP, the isset() function is used to check if a variable is set and is not null. It returns true if the variable exists and has a value other than null; otherwise, it returns false. The primary purpose of isset() is to avoid errors that might occur when trying to access or use a variable that hasn't been defined.

PHP script for the given problem statement

The provided code is designed to resolve the stated problem.

<?php
// Check if the page is accessed using HTTPS
$isHttps = isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] === "on";

if ($isHttps) {
    echo "The page is accessed using HTTPS.";
} else {
    echo "The page is accessed using HTTP.";
}
?>

Output

The output of the given code is:

The page is accessed using HTTP.

Code Explanation

This script uses the $_SERVER['HTTPS'] variable to check whether the request is using a secure connection ('https'). If it's set to 'on', then it's 'https', otherwise, it's 'http'. The script then displays the given message based on the result.

  • $_SERVER['HTTPS']: Accesses the 'HTTPS' key in the $_SERVER superglobal, which typically contains information about the secure connection.
  • isset($_SERVER['HTTPS']): Checks if the 'HTTPS' key is set in the $_SERVER array.
  • $_SERVER['HTTPS'] === 'on': Checks if the value of 'HTTPS' is strictly equal to 'on', indicating a secure (HTTPS) connection.
  • $isHttps = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on';: Combines the above conditions, setting $isHttps to true if 'HTTPS' is set and its value is 'on', otherwise, it sets it to false.

More PHP Programs »

All PHP Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.