How can PHP scripts be utilized to check if a URL starts with "https" and redirect if necessary?

To check if a URL starts with "https" in a PHP script, you can use the strpos function to search for the substring "https://" at the beginning of the URL. If the substring is found, then the URL is already using HTTPS. If not found, you can redirect the user to the HTTPS version of the URL by using the header function to send a 301 redirect status code.

$url = $_SERVER['REQUEST_URI'];

if(strpos($url, 'https://') !== 0){
    $https_url = 'https://' . $_SERVER['HTTP_HOST'] . $url;
    header("HTTP/1.1 301 Moved Permanently");
    header("Location: $https_url");
    exit();
}