What are some best practices for handling user input in PHP scripts to ensure security?

When handling user input in PHP scripts, it is crucial to sanitize and validate the input to prevent security vulnerabilities such as SQL injection, XSS attacks, and CSRF attacks. One of the best practices is to use functions like htmlentities() or htmlspecialchars() to escape user input before using it in SQL queries or outputting it to the browser. Additionally, always use prepared statements when interacting with databases to prevent SQL injection attacks.

// Sanitize user input using htmlentities()
$userInput = htmlentities($_POST['input'], ENT_QUOTES, 'UTF-8');

// Validate user input to ensure it meets specific criteria
if (filter_var($userInput, FILTER_VALIDATE_EMAIL)) {
    // Process the input
} else {
    // Handle invalid input
}