Reviving a Vulnerable PHP Guestbook: A Modernization Case Study

By: fyvo July 28, 2025 PHP

Description

This snippet implements a simple guestbook functionality using outdated PHP and MySQL interaction. It's representative of early web application development practices, highlighting common vulnerabilities.

Code Snippet

```php
<?php

$servername = 'localhost';
$username = 'your_username';
$password = 'your_password';
$dbname = 'your_dbname';

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
    exit();
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = htmlspecialchars($_POST['name']);
    $comment = htmlspecialchars($_POST['comment']);

    $stmt = $conn->prepare("INSERT INTO guestbook (name, comment) VALUES (?, ?)");
    $stmt->execute([$name, $comment]);
}

$stmt = $conn->prepare("SELECT * FROM guestbook");
$stmt->execute();
$guestbookEntries = $stmt->fetchAll(PDO::FETCH_ASSOC);

?>
<!DOCTYPE html>
<html>
<head><title>Guestbook</title></head>
<body>
<h1>Guestbook</h1>
<form method="post">
    Name: <input type="text" name="name"><br>
    Comment: <textarea name="comment"></textarea><br>
    <input type="submit" value="Submit">
</form>

<h2>Entries:</h2>
<ul>
    <?php foreach ($guestbookEntries as $entry): ?>
        <li><strong>Name:</strong> <?= $entry['name'] ?>, <strong>Comment:</strong> <?= $entry['comment'] ?></li>
    <?php endforeach; ?>
</ul>
</body>
</html>
```

Discussion (0)