How can PHP be used to prevent XSS and SQL injection vulnerabilities in user inputs?

To prevent XSS vulnerabilities in user inputs, PHP developers can use the htmlspecialchars() function to encode special characters in the input data. This function converts characters like < and > into their HTML entity equivalents, preventing them from being interpreted as HTML or JavaScript code. To prevent SQL injection vulnerabilities, developers should use prepared statements with parameterized queries when interacting with a database. This technique separates the SQL query from the user input, preventing malicious SQL code from being executed.

// Preventing XSS vulnerabilities
$user_input = &#039;&lt;script&gt;alert(&quot;XSS attack&quot;)&lt;/script&gt;&#039;;
$encoded_input = htmlspecialchars($user_input);
echo $encoded_input;

// Preventing SQL injection vulnerabilities
$conn = new PDO(&quot;mysql:host=localhost;dbname=myDB&quot;, $username, $password);
$stmt = $conn-&gt;prepare(&quot;SELECT * FROM users WHERE username = :username&quot;);
$stmt-&gt;bindParam(&#039;:username&#039;, $user_input);
$stmt-&gt;execute();