Are there any best practices to follow when implementing automatic redirection in PHP?

When implementing automatic redirection in PHP, it is important to ensure that the redirection is done securely to prevent vulnerabilities such as open redirects. One best practice is to always validate and sanitize the input used for the redirection URL to prevent malicious redirects. Additionally, it is recommended to use HTTP status codes (such as 301 or 302) to indicate the type of redirection being performed.

// Securely redirect to a specified URL using HTTP 302 status code
function redirect($url) {
    // Validate and sanitize the URL
    $url = filter_var($url, FILTER_VALIDATE_URL);

    if ($url) {
        header("Location: $url", true, 302);
        exit();
    } else {
        // Handle invalid URL
        echo "Invalid URL";
    }
}

// Example usage
redirect("https://example.com");