Home > Backend Development > PHP Tutorial > How to Reliably Check for HTTPS Connection When $_SERVER['HTTPS'] is Undefined?

How to Reliably Check for HTTPS Connection When $_SERVER['HTTPS'] is Undefined?

DDD
Release: 2024-12-20 16:48:13
Original
412 people have browsed it

How to Reliably Check for HTTPS Connection When $_SERVER['HTTPS'] is Undefined?

Is HTTPS Enabled: Addressing Undefined $_SERVER['HTTPS']

Checking $_SERVER['HTTPS'] remains a common approach to verifying HTTPS connections. However, undefined values in this variable on certain servers can lead to errors. To address this issue, a more reliable alternative method is available.

Solution

This code snippet ensures that HTTPS status can be determined regardless of $_SERVER['HTTPS'] availability:

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

Explanation

The code utilizes two conditions to determine HTTPS status:

  • If $_SERVER['HTTPS'] is defined and its value is not "off," it indicates that the connection is secure.
  • Even if $_SERVER['HTTPS'] is undefined, a check for $_SERVER['SERVER_PORT'] value of 443 (the default HTTPS port) confirms a secure connection.

This method accounts for the potential issues with IIS and Apache 1.x servers, where $_SERVER['HTTPS'] may not be set even with secure connections.

Compatibility

This code is compatible with IIS and Apache servers. Additionally, it is important to note that it checks the connection between the load balancer and the server. For connections between the client and the load balancer, the HTTP_X_FORWARDED_PROTO header can be used, though it requires more complex implementation.

The above is the detailed content of How to Reliably Check for HTTPS Connection When $_SERVER['HTTPS'] is Undefined?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template