What are the best practices for handling URL redirection in PHP applications?

When handling URL redirection in PHP applications, it is important to ensure that the redirection is done securely to prevent vulnerabilities such as open redirects or phishing attacks. It is recommended to use header() function with a proper HTTP status code for redirection, sanitize and validate input before redirecting, and avoid using user input directly in the redirection URL.

// Securely handle URL redirection in PHP
function redirect($url) {
    if (filter_var($url, FILTER_VALIDATE_URL)) {
        header("Location: " . $url, true, 301);
        exit();
    } else {
        // Handle invalid URL
        echo "Invalid URL";
    }
}

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