PHP Snippets: Redirect http to https (php)

<?php
$redirect= false;
    if (!isset($_SERVER['HTTPS'])) {
        $redirect= true;
    } else {
        if ($_SERVER['HTTPS'] != "on")
            $redirect= true;
    }
    if ($redirect) {
        $url = "https://" . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
        header("HTTP/1.1 301 Moved Permanently");
        header("Location: ".$url); 
        exit();
    }
?>