How can PHP developers ensure the security of their code?

PHP developers can ensure the security of their code by implementing proper input validation, using prepared statements to prevent SQL injection attacks, escaping output to prevent cross-site scripting (XSS) attacks, and keeping PHP and its dependencies up to date to patch any security vulnerabilities.

// Example of input validation to prevent SQL injection
$username = mysqli_real_escape_string($conn, $_POST['username']);
$password = mysqli_real_escape_string($conn, $_POST['password']);

// Example of using prepared statements to prevent SQL injection
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);
$stmt->execute();
$result = $stmt->get_result();

// Example of escaping output to prevent XSS attacks
echo htmlspecialchars($user_input, ENT_QUOTES, 'UTF-8');