Are there any security considerations to keep in mind when implementing URL redirection in PHP?

When implementing URL redirection in PHP, it is important to validate and sanitize the input URL to prevent malicious redirects. This can help protect against attacks such as open redirect vulnerabilities where an attacker can trick users into visiting malicious websites. One way to mitigate this risk is to ensure that the redirect URL is a trusted and whitelisted domain.

// Example of validating and sanitizing the input URL before redirection
$redirectUrl = filter_var($_GET['redirect'], FILTER_SANITIZE_URL);

$allowedDomains = ['example.com', 'trustedsite.com'];
$isValidRedirect = false;

foreach ($allowedDomains as $domain) {
    if (strpos($redirectUrl, $domain) !== false) {
        $isValidRedirect = true;
        break;
    }
}

if ($isValidRedirect) {
    header("Location: $redirectUrl");
} else {
    echo "Invalid redirect URL";
}