How can the URL be checked and redirected to HTTPS if it does not already contain it in PHP?

To check and redirect a URL to HTTPS in PHP, you can use the $_SERVER['HTTPS'] variable to determine if the current request is using HTTPS. If it is not, you can redirect the user to the HTTPS version of the URL using the header() function.

if(empty($_SERVER['HTTPS']) || $_SERVER['HTTPS'] == "off") {
    $redirect_url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
    header("Location: $redirect_url");
    exit();
}