php detect https | php detect http or https | php check if url contains http or https

PHP detect https sample code 2021

For the last couple of years, we use to hear that security is an essential factor. Even if it’s a small site that contains a couple of pages, security is necessary.

I will let you know how PHP detects HTTPS.

Additionally, we should know about the super global variable in PHP. It’s available in all scope.

More common know super variable are below.
$GLOBALS.
$_SERVER.
$_REQUEST.
$_POST.
$_GET.
$_FILES.
$_ENV.
$_COOKIE

We must have an SSL certificate install on the server. We can check using $_SERVER[‘HTTPS’].

Out put of $_SERVER.

As we can see if we output $_SERVER. It would show the value of HTTPS. In this case its on so HTTPS is available.

php detect https using super global variable

<?php 

if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' && $_SERVER['REQUEST_SCHEME'] === 'https' ) {
    echo "HTTPS available";
}else{
    echo "HTTPS not available";	
}

?>

Using SERVER_PORT check http or https in PHP

<?php 

if (isset($_SERVER['SERVER_PORT'])) {
	if ('443' == $_SERVER['SERVER_PORT']) {
		echo "https request";
	}elseif (isset($_SERVER['SERVER_PORT'])) {
	   echo "http request";
	}
}

?>

Check if URL has http or https

<?php
$currentPageURL = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

$url = parse_url($currentPageURL);

if($url['scheme'] == 'https'){
   echo "https url";
}else{
   echo "http url";
}
?>

Don’t forget to check Why do we use the Final keyword in PHP?

2 thoughts on “PHP detect https sample code 2021”

  1. Pingback: Code to display category name in WordPress - PHPPanda.com

  2. Pingback: Check If URL Contains String with PHP8 - PHPPanda.com

Leave a Comment

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