What are the best practices for handling user input in PHP to prevent malicious code execution?

To prevent malicious code execution through user input in PHP, it is crucial to sanitize and validate all incoming data. One common practice is to use functions like htmlspecialchars() to escape special characters and prevent XSS attacks. Additionally, parameterized queries should be used when interacting with databases to prevent SQL injection attacks.

// Example of sanitizing user input using htmlspecialchars()
$user_input = "<script>alert('XSS attack!');</script>";
$clean_input = htmlspecialchars($user_input, ENT_QUOTES, 'UTF-8');
echo $clean_input;