What are some best practices for ensuring PHP guestbook scripts are secure and protect against common vulnerabilities like XSS and CSRF attacks?

To protect against XSS attacks in PHP guestbook scripts, it is important to properly sanitize user input before displaying it on the page. This can be done by using functions like htmlentities() or htmlspecialchars() to encode special characters. Additionally, to prevent CSRF attacks, it is recommended to include a hidden CSRF token in forms and validate it on form submission.

// Sanitize user input to prevent XSS attacks
$name = htmlentities($_POST['name']);
$message = htmlspecialchars($_POST['message']);

// Generate and validate CSRF token
$token = bin2hex(random_bytes(32));
$_SESSION['csrf_token'] = $token;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
        // Invalid CSRF token, handle accordingly
    }
}