What are the potential pitfalls of manually changing the target URL for redirection in PHP scripts?

Changing the target URL for redirection manually in PHP scripts can lead to security vulnerabilities such as open redirect attacks, where an attacker can manipulate the URL to redirect users to malicious websites. To prevent this, always validate and sanitize user input before using it to redirect users.

// Validate and sanitize the target URL before redirection
$targetUrl = filter_var($_GET['url'], FILTER_SANITIZE_URL);

// Redirect to the sanitized target URL
header("Location: " . $targetUrl);
exit();