How can PHP developers prevent cross-site scripting attacks in their code, especially when handling user input like in a guestbook form?

Cross-site scripting attacks can be prevented in PHP code by properly sanitizing and validating user input before displaying it on the webpage. One way to do this is by using functions like htmlspecialchars() to encode special characters in the input. Additionally, developers should avoid echoing user input directly onto the page without proper validation.

// Sanitize and validate user input in a guestbook form
$name = htmlspecialchars($_POST['name']);
$message = htmlspecialchars($_POST['message']);

// Insert the sanitized input into the database or display it on the webpage