What are some best practices for securing input fields from HTML code manipulation in PHP?

When working with input fields in PHP, it is essential to sanitize and validate user input to prevent HTML code manipulation, which can lead to security vulnerabilities such as cross-site scripting attacks. One way to secure input fields is by using the htmlspecialchars() function to convert special characters to HTML entities, ensuring that any HTML code entered by the user is displayed as plain text.

// Sanitize and validate user input from an input field
$input = $_POST['input_field'];

// Sanitize input to prevent HTML code manipulation
$sanitized_input = htmlspecialchars($input);

// Use the sanitized input in your application
echo "Sanitized input: " . $sanitized_input;