How can SQL injection and XSS vulnerabilities be mitigated in PHP code?

SQL injection vulnerabilities can be mitigated in PHP code by using prepared statements with parameterized queries instead of concatenating user input directly into SQL queries. This helps prevent malicious SQL code from being injected into the query. XSS vulnerabilities can be mitigated by properly escaping user input before displaying it on a webpage. This can be done using functions like htmlspecialchars() to encode special characters in the input. Example PHP code snippet using prepared statements to prevent SQL injection:

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

// Prepare a SQL statement with a placeholder for user input
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');

// Bind the user input to the placeholder
$stmt->bindParam(':username', $_POST['username']);

// Execute the statement
$stmt->execute();

// Fetch the results
$results = $stmt->fetchAll();
```

Example PHP code snippet using htmlspecialchars() to prevent XSS:

```php
// Get user input
$userInput = $_POST['input'];

// Escape user input before displaying it on a webpage
$escapedInput = htmlspecialchars($userInput);

// Display the escaped input
echo $escapedInput;