What are some best practices for handling redirects in PHP scripts to ensure immediate execution?

When handling redirects in PHP scripts, it is important to ensure that the redirection happens immediately without any further processing of the current script. To achieve this, you can use the header() function in PHP to send a raw HTTP header for the redirect. This will instruct the browser to immediately redirect to the specified location.

<?php
// Perform any necessary checks or processing before redirecting
// For example, check if user is logged in or has necessary permissions

if($redirect_needed) {
    header("Location: http://www.example.com/new_page.php");
    exit; // Ensure immediate execution after redirect
}

// Continue with the rest of the script if no redirect is needed
?>