What are the potential pitfalls of using header redirects in PHP applications?

Potential pitfalls of using header redirects in PHP applications include the risk of header injection attacks, as well as the possibility of causing unintended side effects or breaking the application's flow. To mitigate these risks, it is important to sanitize and validate any user input that is used in the redirect URL.

// Sanitize and validate the redirect URL before using it in a header redirect
$redirectUrl = filter_var($_GET['redirect_url'], FILTER_SANITIZE_URL);

if (filter_var($redirectUrl, FILTER_VALIDATE_URL)) {
    header("Location: $redirectUrl");
    exit;
} else {
    // Handle invalid redirect URL
    echo "Invalid redirect URL";
}