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

Mary-Kate Olsen
Release: 2024-10-27 16:58:02
Original
775 people have browsed it

 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() );
Copy after login

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() );
Copy after login

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://';
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!