What steps can be taken in PHP code to validate and sanitize user input, especially when dealing with special characters like Umlauts?

When dealing with user input, especially special characters like Umlauts, it is important to validate and sanitize the input to prevent security vulnerabilities such as SQL injection or cross-site scripting attacks. One way to do this is by using PHP's filter_var() function with the FILTER_SANITIZE_STRING filter to remove any potentially harmful characters. Additionally, you can also use htmlentities() function to convert special characters into their HTML entities to prevent any malicious code execution.

// Validate and sanitize user input with special characters like Umlauts
$userInput = $_POST['user_input'];

// Validate and sanitize user input
$cleanInput = filter_var($userInput, FILTER_SANITIZE_STRING);

// Convert special characters into HTML entities
$cleanInput = htmlentities($cleanInput, ENT_QUOTES, 'UTF-8');

// Now $cleanInput is safe to use in your application