What are the potential pitfalls of using variables in header(Location: URL) in PHP?

Using variables in the header(Location: URL) function in PHP can lead to potential security vulnerabilities, such as header injection attacks. To prevent this, always sanitize and validate user input before using it in the header function. Additionally, make sure to use absolute URLs to avoid any unexpected behavior.

// Sanitize and validate user input before using it in header function
$redirectUrl = filter_var($_GET['redirect_url'], FILTER_SANITIZE_URL);
if (filter_var($redirectUrl, FILTER_VALIDATE_URL)) {
    header("Location: " . $redirectUrl);
    exit();
} else {
    echo "Invalid URL";
}