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:
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!