Secure Modern Guestbook: From Legacy PHP to Robust Application

By: fyvo July 28, 2025 PHP

Description

This snippet implements a simple guestbook using PHP and file storage. Its historical significance lies in demonstrating early web application development, but it severely lacks security and scalability.

Original Code (Outdated)

```php
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
  $name = $_POST['name'];
  $comment = $_POST['comment'];
  $entry = "$name: $comment\n";
  file_put_contents('guestbook.txt', $entry, FILE_APPEND);
}
?>
<html><body><h1>Guestbook</h1><form method="post">
Name: <input type="text" name="name"><br>
Comment: <textarea name="comment"></textarea><br><input type="submit"></form>
</body></html>
```

Updated Code (Modern)

```php
<?php

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Sanitize user inputs
    $name = htmlspecialchars($_POST['name'], ENT_QUOTES, 'UTF-8');
    $comment = htmlspecialchars($_POST['comment'], ENT_QUOTES, 'UTF-8');

    //  Better approach would be to use a database here
    //  Example using a database (replace with your database credentials)
    // $conn = new mysqli('localhost', 'username', 'password', 'guestbook_db');
    // $stmt = $conn->prepare('INSERT INTO guestbook (name, comment) VALUES (?, ?)');
    // $stmt->bind_param('ss', $name, $comment);
    // $stmt->execute();
    // $stmt->close();
    // $conn->close();

    $entry = "$name: $comment\n";
    //Error Handling
    if (file_put_contents('guestbook.txt', $entry, FILE_APPEND) === false) {
        error_log("Error writing to guestbook.txt");
    }
}
?>
<html><body><h1>Guestbook</h1><form method="post">
Name: <input type="text" name="name"><br>
Comment: <textarea name="comment"></textarea><br><input type="submit"></form>
</body></html>
```

Discussion (0)