Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting HTTPS requests in PHP

Tags:

The problem that I am having has to do with the need to keep some urls of a website protected by HTTPS and the rest kicked to HTTP.

Normally, you have $_SERVER['HTTP_HTTPS'] or $_SERVER['HTTPS'] (depending on your flavor of Apache). You also can check the port - it's 80 for normal traffic and 443 for HTTPS.

My problem is that the certificate sits on the loadbalancer, and all these variables are unavailable, and the webserver sees http://www.foo.com on port 80. One way to fix this is to tell the loadbalancer to send the traffic on a different port, but I wonder if there are other ways to detect HTTPS coming from the load balancer?

like image 347
deadprogrammer Avatar asked Jan 16 '09 23:01

deadprogrammer


People also ask

How to find HTTPS in PHP?

Approach 1: Check if the connection is using SSL and if the value of $_SERVER['HTTPS'] is set, then we can say that the connection is secured and called from 'HTTPS'.

How do I know if https is requested?

You'll want to verify that $_SERVER['HTTPS'] exists and is non-empty. In cases where HTTPS is not set correctly for a given server, you can try checking if $_SERVER['SERVER_PORT'] == 443 .

How to check site is HTTP or HTTPS?

Fortunately, there are two quick checks to help you be certain: Look at the uniform resource locator (URL) of the website. A secure URL should begin with “https” rather than “http.” The “s” in “https” stands for secure, which indicates that the site is using a Secure Sockets Layer (SSL) Certificate.


1 Answers

If anybody has the same issue behind an Amazon AWS Elastic Load Balancer, the solution is simple because the $_SERVER variable will include:

[HTTP_X_FORWARDED_PORT] => 443
[HTTP_X_FORWARDED_PROTO] => https

So, to get the protocol, you could use:

function getRequestProtocol() {
    if(!empty($_SERVER['HTTP_X_FORWARDED_PROTO']))
        return $_SERVER['HTTP_X_FORWARDED_PROTO'];
    else 
        return !empty($_SERVER['HTTPS']) ? "https" : "http";
}
like image 116
mrucci Avatar answered Nov 06 '22 12:11

mrucci