PHP: HTTP or HTTPS?

In PHP, you can use the $_SERVER['HTTPS'] variable to check whether the current page is being served over HTTPS. If the variable is set and has a value of 'on', the page is being served over HTTPS.

You can also use the $_SERVER['SERVER_PORT'] variable to check the port number being used for the current connection. Port 443 is the default port for HTTPS connections, so if the value of this variable is 443, the page is likely being served over HTTPS.

Watch a course Learn object oriented PHP

PHP also provides a function called https_request() which can be used to check whether the current page is being served over HTTPS.

With PHP you can also redirect user to HTTPS version of your website by using a simple code snippet in the beginning of your script or in htaccess file

<?php

if ($_SERVER['HTTPS'] != "on") {
    $url = "https://" . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
    header("Location: $url");
    exit();
}

This will redirect all the incoming request to HTTPS version of the website.

It is important to note that if you are using a load balancer or a reverse proxy, it may handle the SSL termination, in that case you will have to check for the headers set by load balancer or proxy for identifying whether the request is coming in over HTTPS or not.