Reviving a Vulnerable PHP Guestbook
Description
This legacy PHP guestbook script demonstrates common vulnerabilities from the early 2000s. It directly inserts user input into SQL queries, leaving it susceptible to SQL injection.
Original Code (Outdated)
<?php
$name = $_POST['name'];
$comment = $_POST['comment'];
$conn = mysql_connect('localhost', 'user', 'password');
mysql_select_db('guestbook', $conn);
$sql = "INSERT INTO entries (name, comment) VALUES ('" . $name . "', '" . $comment . "')";
mysql_query($sql, $conn);
mysql_close($conn);
?>
Updated Code (Modern)
<?php
$name = htmlspecialchars($_POST['name'], ENT_QUOTES, 'UTF-8');
$comment = htmlspecialchars($_POST['comment'], ENT_QUOTES, 'UTF-8');
$conn = new mysqli('localhost', 'user', 'password', 'guestbook');
if ($conn->connect_error) {
die('Connection failed: ' . $conn->connect_error);
}
$stmt = $conn->prepare("INSERT INTO entries (name, comment) VALUES (?, ?)");
if (!$stmt) {
die('Prepare failed: ' . $conn->error);
}
$stmt->bind_param('ss', $name, $comment);
if (!$stmt->execute()) {
die('Execute failed: ' . $stmt->error);
}
$stmt->close();
$conn->close();
?>