Reviving a Vulnerable PHP Guestbook: A Modernization Journey

By: fyvo July 28, 2025 PHP

Description

This snippet demonstrates a simple PHP guestbook implementation from the early 2000s. Its vulnerabilities highlight the importance of secure coding practices in web development.

Original Code (Outdated)

```php
<?php
$name = $_POST['name'];
$comment = $_POST['comment'];
mysql_connect('localhost', 'your_db_user', 'your_db_password') or die(mysql_error());
mysql_select_db('your_db_name') or die(mysql_error());
$query = "INSERT INTO guestbook (name, comment) VALUES ('$name', '$comment')";
mysql_query($query) or die(mysql_error());
$result = mysql_query("SELECT * FROM guestbook");
while ($row = mysql_fetch_array($result)) {
  echo "<p><b>" . $row['name'] . "</b>: " . $row['comment'] . "</p>";
}
mysql_close();
?>
```

Updated Code (Modern)

```php
<?php

// Database credentials (move to a secure configuration file)
define('DB_HOST', 'localhost');
define('DB_USER', 'your_db_user');
define('DB_PASS', 'your_db_password');
define('DB_NAME', 'your_db_name');

// Create a database connection using prepared statements
try {
    $mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
    if ($mysqli->connect_error) {
        throw new Exception('Connection failed: ' . $mysqli->connect_error);
    }
} catch (Exception $e) {
    die('Database error: ' . $e->getMessage());
}

// Input sanitization and validation
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = $mysqli->real_escape_string(trim($_POST['name']));
    $comment = $mysqli->real_escape_string(trim($_POST['comment']));

    // Prepared statement to prevent SQL injection
    $stmt = $mysqli->prepare("INSERT INTO guestbook (name, comment) VALUES (?, ?)");
    $stmt->bind_param('ss', $name, $comment);
    $stmt->execute();
    $stmt->close();
}

// Fetch and display guestbook entries
$result = $mysqli->query("SELECT * FROM guestbook");
while ($row = $result->fetch_assoc()) {
    echo "<p><b>" . htmlspecialchars($row['name']) . "</b>: " . htmlspecialchars($row['comment']) . "</p>";
}

$mysqli->close();
?>
```

Discussion (0)