How can PHP be used to validate and sanitize user input from HTML forms?

When working with HTML forms, it is crucial to validate and sanitize user input to prevent security vulnerabilities such as SQL injection and cross-site scripting attacks. PHP provides built-in functions for validating and sanitizing user input, such as filter_input() and htmlspecialchars(). By using these functions, you can ensure that the data submitted through HTML forms is safe to use in your application.

// Validate and sanitize user input from an HTML form
$name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING);
$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);

// Sanitize user input to prevent XSS attacks
$message = htmlspecialchars($_POST['message']);