Home  >  Article  >  Backend Development  >  How to Determine the Current Site URL Protocol in PHP: Is this Function Correct?

How to Determine the Current Site URL Protocol in PHP: Is this Function Correct?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-27 16:58:02776browse

 How to Determine the Current Site URL Protocol in PHP: Is this Function Correct?

PHP Get Site URL Protocol - http vs https

Question:

A user has created a function to establish the current site URL protocol but is unsure if it works under HTTPS since they don't have SSL. They ask if their function is correct:

function siteURL()
{
    $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
    $domainName = $_SERVER['HTTP_HOST'].'/';
    return $protocol.$domainName;
}
define( 'SITE_URL', siteURL() );

They also wonder if they can simplify the function as follows:

function siteURL()
{
    $protocol = 'http://';
    $domainName = $_SERVER['HTTP_HOST'].'/'
    return $protocol.$domainName;
}
define( 'SITE_URL', siteURL() );

Answer:

The provided function is correct and can effectively determine the protocol (http or https) based on the following conditions:

  • If $_SERVER['HTTPS'] is not empty and not equal to 'off'
  • If $_SERVER['SERVER_PORT'] is equal to 443

However, there is a more concise way to achieve the same result:

if (isset($_SERVER['HTTPS']) &&
    ($_SERVER['HTTPS'] == 'on' || $_SERVER['HTTPS'] == 1) ||
    isset($_SERVER['HTTP_X_FORWARDED_PROTO']) &&
    $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') {
  $protocol = 'https://';
}
else {
  $protocol = 'http://';
}

This snippet of code checks for both the presence of $_SERVER['HTTPS'] and whether its value is 'on' or 1. It also checks for the presence of $_SERVER['HTTP_X_FORWARDED_PROTO'] and whether its value is 'https'. This scenario occurs when the website uses HTTPS, but the protocol is not directly accessible via $_SERVER['HTTPS'].

The above is the detailed content of How to Determine the Current Site URL Protocol in PHP: Is this Function Correct?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn