What are some potential pitfalls when using variables in Header Location in PHP?

One potential pitfall when using variables in Header Location in PHP is that the variable may not be properly sanitized, leading to security vulnerabilities such as header injection attacks. To avoid this, always sanitize and validate user input before using it in the Header Location.

// Example of properly sanitizing and validating a variable before using it in Header Location

// Retrieve user input from a form
$userInput = $_POST['user_input'];

// Sanitize and validate the user input
$validatedInput = filter_var($userInput, FILTER_SANITIZE_STRING);

// Redirect using the validated input
header("Location: example.php?input=" . urlencode($validatedInput));
exit;