Jop Holp
Jop Holp

Reputation: 53

PHP - How to redirect to https if available?

I know how to redirect to https with PHP, but does anyone know how to redirect only if the site is requested via HTTP and HTTPS is available on the server?

Upvotes: 1

Views: 209

Answers (3)

Waqas Ahmed
Waqas Ahmed

Reputation: 17

$via_http = (isset($_SERVER['REQUEST_SCHEME']) && $_SERVER['REQUEST_SCHEME'] == 'http') ? true : false;
$https_available = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') ? true : false;
if ($via_http && $https_available) {
    $location = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
    header('Location: ' . $location);
}

This will make sure

1 : The request is from/via http page and not https.

2 : HTTPS is available on server.

3 : Redirect to https only one time and Avoid redirecting infinitely.

Upvotes: 0

Jojo
Jojo

Reputation: 2760

I don't know of a way to check a server's available protocols via php. Also, if there is one, you get lost when you want to check and redirect to a remote server. So in order to check wether your destination server is capable of handling https request you need to query it. Here is an example with php-curl:

<?php
/**
 * Check wether a destination is reachable.
 * 
 * @param string $uri uri to check
 * 
 * @return bool
 */
function checkAvailability($uri) {
    $handle = curl_init($uri);
    curl_setopt_array($handle, [
        CURLOPT_RETURNTRANSFER  => 1,
        CURLOPT_USERAGENT       => 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.1'
        ]);
    $r = curl_exec($handle);
    $responseCode = (int)curl_getinfo($handle, CURLINFO_HTTP_CODE);
    curl_close($handle);
    return $responseCode > 199 && $responseCode < 400;
}

//we test by checking the webpages of two of my local newspapers, l-iz.de will succeed, lvz.de will not
var_dump(checkAvailability('https://www.l-iz.de'));
var_dump(checkAvailability('https://lvz.de'));

The method checkAvailability simple tests if a curling url returns a success HTTP-Code between 200 and 399. This is not as accurate as it could be, but shall be sufficient for this use case. So if you call this method with a https url you get your desired info wether a webserver accepts https traffic

Upvotes: 1

Sabin Chacko
Sabin Chacko

Reputation: 761

Please have a look at this..

<?php
if (isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] == 'on' || $_SERVER['HTTPS'] == 1) || isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') {
    // Enter 'https' URL here...(Eg: https://google.com)
} else {
    // Enter 'http' URL here... (Eg: http://google.com)
}
?>

Upvotes: 0

Related Questions