What are the potential pitfalls of using PHP for URL redirection?

One potential pitfall of using PHP for URL redirection is the possibility of introducing security vulnerabilities, such as open redirects or header injection attacks. To mitigate these risks, it is important to validate and sanitize user input before using it in a redirect function. Additionally, using a whitelist approach for allowed URLs can help prevent unauthorized redirects.

// Validate and sanitize user input for URL redirection
$redirect_url = filter_var($_GET['url'], FILTER_SANITIZE_URL);

// Whitelist of allowed URLs
$allowed_urls = array('https://example.com/page1', 'https://example.com/page2');

// Check if the redirect URL is in the whitelist
if (in_array($redirect_url, $allowed_urls)) {
    header("Location: $redirect_url");
    exit();
} else {
    // Redirect to a default URL if the input is not valid
    header("Location: https://example.com/default");
    exit();
}