Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use PHP to check if page was accessed with SSL

Tags:

php

ssl

Is there a way to check if the current page was opened with SSL? For example, I want my login page (login.php) to check if it was accessed using SSL (https://mywebserver.com/login.php). If not, redirect them to the SSL version of the page.

Pretty much, I want to enfore that the user uses the page securely.

like image 365
Spidy Avatar asked Feb 24 '11 03:02

Spidy


People also ask

How do you check whether the page is called from HTTPS or HTTP 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'. If the value is empty, this means the value is set to '0' or 'off' then we can say that the connection is not secured and the page is called from 'HTTP'.

Does PHP use HTTPS?

There is no PHP code change involved. HTTPS means the data that the communication between the browser and the webserver will be encrypted. The browser is already setup for HTTPS, all you have to do is to configure your web server.

How do I know if a website 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.

What is $_ server [' HTTPS ']?

$_SERVER['HTTPS']; As per the php docs, if the connection is using SSL/TLS then the value of $_SERVER['HTTPS'] is set to a non-empty value (such as on , 1 , etc. depending on the web server configuration).


2 Answers

You should be able to check that $_SERVER['HTTPS'] is set, e.g.:

if (empty($_SERVER['HTTPS'])) {     header('Location: https://mywebserver.com/login.php');     exit; } 
like image 114
Long Ears Avatar answered Sep 20 '22 11:09

Long Ears


Be careful. On my IIS server, $_SERVER['HTTPS'] is not empty but has the value 'off'.

So i had to do

if (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != 'on') {     // no SSL request } 
like image 24
Baptiste Ménadier Avatar answered Sep 19 '22 11:09

Baptiste Ménadier