What are the potential security risks of allowing JavaScript and HTML in guestbook entries, and how can they be prevented?

Allowing JavaScript and HTML in guestbook entries can pose security risks such as cross-site scripting (XSS) attacks, where malicious scripts are executed in users' browsers. To prevent this, input validation and sanitization should be implemented to strip out any potentially harmful code.

// Sanitize and validate guestbook entry before saving to database
$guestbook_entry = htmlspecialchars($_POST['guestbook_entry']);
$guestbook_entry = strip_tags($guestbook_entry, '<b><i><u>'); // Allow only certain HTML tags
// Save sanitized entry to database