How can you prevent header injection attacks when using the header function in PHP?

Header injection attacks can be prevented by validating and sanitizing user input before using it in the header function. This can be done by checking for any potentially malicious characters such as newlines or carriage returns in the input.

// Validate and sanitize user input before using it in the header function
$user_input = $_POST['user_input'];

if (preg_match('/[\r\n]/', $user_input)) {
    // Input contains potentially malicious characters, handle error
    echo "Invalid input detected";
} else {
    // Safe to use input in header function
    header("Location: " . $user_input);
}