What are the best practices for handling user input in PHP to prevent hacking attempts?

User input in PHP should always be sanitized and validated to prevent hacking attempts such as SQL injection, cross-site scripting (XSS), and other malicious attacks. To handle user input securely, use functions like htmlspecialchars() to prevent XSS attacks, and prepared statements or parameterized queries to prevent SQL injection.

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

// Validate user input to prevent SQL injection
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
$stmt->bindParam(':username', $userInput);
$stmt->execute();