Are there best practices for securely handling user input data in PHP scripts?

When handling user input data in PHP scripts, it is crucial to sanitize and validate the input to prevent security vulnerabilities such as SQL injection, cross-site scripting (XSS), and other attacks. Best practices include using functions like htmlspecialchars() to escape HTML characters, validating input using functions like filter_var(), and using prepared statements when interacting with databases to prevent SQL injection.

// Example of securely handling user input data in PHP

// Sanitize user input data
$userInput = "<script>alert('XSS attack');</script>";
$cleanInput = htmlspecialchars($userInput, ENT_QUOTES);

// Validate user input data
$email = "invalidemail";
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo "Valid email address";
} else {
    echo "Invalid email address";
}

// Using prepared statements to prevent SQL injection
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
$stmt->bindParam(':username', $username);
$username = "admin";
$stmt->execute();
$results = $stmt->fetchAll();