Skip to content
PHP Logo

What potential security risks are present in the code provided for uploading and displaying images from a database?

The code provided does not have any input validation or sanitization, leaving it vulnerable to SQL injection attacks. To mitigate this risk, we should use prepared statements when interacting with the database to prevent malicious SQL queries from being executed.

php
// Original code for uploading and displaying images from a database
// Vulnerable to SQL injection attacks

// Fix: Use prepared statements to prevent SQL injection attacks

// Upload image
$stmt = $pdo->prepare("INSERT INTO images (image_name) VALUES (:image_name)");
$stmt->bindParam(':image_name', $image_name);
$stmt->execute();

// Display image
$stmt = $pdo->prepare("SELECT image_name FROM images WHERE id = :id");
$stmt->bindParam(':id', $id);
$stmt->execute();
$image = $stmt->fetch();
echo '<img src="images/' . $image['image_name'] . '" alt="Uploaded Image">';