Check if the page called from HTTP or HTTPS in PHP

We often find websites which may contain HTTP or HTTPS protocol. These indicate if a website is sucure or not with SSL. Now, in this article, we are going to learn how to check if the web page called from HTTP or HTTPS in PHP.

It may often be needed to detect if the page request is HTTPS or not to perform task relate to web security. So we are going to learn how to detect if the request is HTTPS or not.

To do this task we are going to check the PHP $_SERVER global variable. You can learn about this global variable from the official PHP website. This variable has the information which we can use to determine if the page is secure with HTTPS or not.

Below is our PHP code to detect if the page has HTTP or HTTPS:

<?php

if( (empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'off') || $_SERVER['SERVER_PORT'] != 443 )
{
  // Redirect to secure site
    header("HTTP/1.1 301 Moved Permanently"); 
    header("Location: https://www.your-domain.com"); 
    exit();
} else {
  // Do nothing when it is a secure site
}

?>

So what we did in our above code?

We have checked if the page is not secure with HTTPS or by checking $_SERVER[‘HTTPS’] and $_SERVER[‘SERVER_PORT’]. In our, if else statement, we have checked if $_SERVER[‘HTTPS’] is empty and it is off or $_SERVER[‘SERVER_PORT’] is not equal to 443.

 

Also, read:

 

Now let me tell you what we did in general.

If our web page called via HTTP, we are redirecting to our secure HTTPS version of the site using the PHP header redirection. Otherwise, we do nothing if the page already called from HTTPS.

Now you can also perform the above code and modify it as your requirement. You can do whatever you want if the page called from HTTP or HTTPS just by putting your own code in the if else statement.

One response to “Check if the page called from HTTP or HTTPS in PHP”

  1. sacasc says:

    ascasc

Leave a Reply

Your email address will not be published. Required fields are marked *