Reviving a Vulnerable PHP Guestbook: A Modernization Case Study
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.
Original Code (Outdated)
```php
<?php
$db = mysql_connect('localhost', 'your_username', 'your_password') or die('Could not connect: ' . mysql_error());
mysql_select_db('your_dbname', $db) or die('Could not select database');
if (isset($_POST['name']) && isset($_POST['comment'])) {
$name = $_POST['name'];
$comment = $_POST['comment'];
mysql_query("INSERT INTO guestbook (name, comment) VALUES ('$name', '$comment')");
}
$result = mysql_query('SELECT * FROM guestbook');
while ($row = mysql_fetch_assoc($result)) {
echo "Name: " . $row['name'] . ", Comment: " . $row['comment'] . "<br>";
}
?>
```
Updated Code (Modern)
```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>
```