What are some best practices for handling user input data in PHP to prevent XSS and SQL injection?

To prevent XSS and SQL injection attacks in PHP, it is essential to sanitize and validate user input data before using it in SQL queries or displaying it on a webpage. This can be achieved by using functions like htmlspecialchars() to escape HTML entities and prepared statements to prevent SQL injection.

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

// Establish a database connection
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');

// Use prepared statements to prevent SQL injection
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');
$stmt->bindParam(':username', $user_input);
$stmt->execute();

// Fetch and display the results
while ($row = $stmt->fetch()) {
    echo $row['username'];
}