What are the best practices for handling user input in PHP to prevent SQL injection and cross-site scripting attacks?

To prevent SQL injection attacks in PHP, it is important to use prepared statements with parameterized queries when interacting with a database. This helps to sanitize user input and prevent malicious SQL queries from being executed. Additionally, to prevent cross-site scripting attacks, it is important to sanitize and validate user input before displaying it on a webpage to ensure that any potentially harmful scripts are not executed.

// Example of 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', $_POST['username']);
$stmt->execute();
```

```php
// Example of sanitizing user input to prevent cross-site scripting
$username = htmlspecialchars($_POST['username']);
echo "Hello, " . $username;