What potential pitfalls should be considered when using variables in the header function for redirection in PHP?

When using variables in the header function for redirection in PHP, it's important to properly sanitize and validate the input to prevent security vulnerabilities such as header injection attacks. Always make sure that the variable value is safe to be used in the header function to avoid unexpected behavior or errors.

// Example of properly sanitizing and validating a variable before using it in the header function for redirection

// Assuming $url is the variable containing the URL to redirect to
if (filter_var($url, FILTER_VALIDATE_URL)) {
    header("Location: " . $url);
    exit();
} else {
    // Handle invalid URL input
    echo "Invalid URL";
}