How can PHP developers protect against XSS and SQL Injection attacks in their code?
To protect against XSS and SQL Injection attacks in PHP code, developers should sanitize user input data and use parameterized queries when interacting with databases. Sanitizing input involves filtering out potentially harmful characters or encoding them to prevent injection attacks. Parameterized queries help prevent SQL Injection by separating SQL code from user input.
// Sanitize user input data
$unsafe_input = $_POST['user_input'];
$safe_input = htmlspecialchars($unsafe_input);
// Use parameterized queries to prevent SQL Injection
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
$stmt->bindParam(':username', $safe_input);
$stmt->execute();