Home > Backend Development > PHP Tutorial > How Can I Reliably Detect HTTPS Usage Without Relying on $_SERVER['HTTPS']?

How Can I Reliably Detect HTTPS Usage Without Relying on $_SERVER['HTTPS']?

Barbara Streisand
Release: 2024-12-20 04:20:12
Original
886 people have browsed it

How Can I Reliably Detect HTTPS Usage Without Relying on $_SERVER['HTTPS']?

Alternative Method to Determine HTTPS Usage Without $_SERVER['HTTPS']

Traditional approaches to verifying HTTPS connections involve checking the value of $_SERVER['HTTPS']. However, on certain server configurations, this variable may not be defined, leading to errors.

Solution

To address this issue, the following function provides a reliable alternative for determining HTTPS connections:

function isSecure() {
  return
    (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')
    || $_SERVER['SERVER_PORT'] == 443;
}
Copy after login

Compatibility and Explanation

  • The code accommodates IIS configurations where $_SERVER['HTTPS'] is set to "off" for non-HTTPS requests.
  • Additionally, it checks the server port (typically 443 for HTTPS connections) as a backup if $_SERVER['HTTPS'] is undefined or invalid.

Note for Load Balancers

This code only tests connections between the server and load balancer if a load balancer is present. For testing connections between the client and load balancer, the HTTP_X_FORWARDED_PROTO header should be utilized, although this approach is more intricate.

The above is the detailed content of How Can I Reliably Detect HTTPS Usage Without Relying on $_SERVER['HTTPS']?. 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