What are the best practices for handling HTTPS redirection in PHP?

When handling HTTPS redirection in PHP, it is important to ensure that all traffic is secure by redirecting users from HTTP to HTTPS. This can be achieved by checking if the current request is not secure and then redirecting to the HTTPS version of the URL.

// Check if the request is not secure
if (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] !== 'on') {
    // Redirect to the HTTPS version of the URL
    header('Location: https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
    exit();
}