简体   繁体   中英

How to display single image from database using php?

I am trying to display single image from database in index.php. Database is connected successfully. but, unfortunately, the image didn't show. I don't know where is my mistake in the code. May I have help please. Database name "newss" Table name "main_img" include 4 columns (id(int), title(varchar), source(varchar), image(blob)) my code blow:

//getImage.php
<?php
require_once('connection.php');
if(isset($_GET['id']))
{
    $id = mysqli_real_escape_string($_GET['id']);
    $query = mysqli_query("SELECT * FROM `main_img` WHERE `id`='$id'");
    while($row = mysqli_fetch_assoc($query))
    {
        $imageData = $row["image"];
    }
    header ("content-type: image/jpeg");
}
else
{
  echo "Error! in retrive the image ";
}
?>

//index.php 
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>Hello in the page of displaying the image </h1>
    <img src="getImage.php?id=2">
</body>
</html>

@mpm already answered your question but your code is vulnerable to SQL Injection . This is a very serious vulnerability in you website as attackers can use it to read your entire database.

More in-depth info here: https://owasp.org/www-community/attacks/SQL_Injection

The important thing is that the user can control the $id variable that you use in $query = mysqli_query("SELECT * FROM `main_img` WHERE `id`='$id'"); This way the attacker can change the query at that point. He could for example use the payload ' UNION SELECT * FROM users to add all user information (passwords, emails, etc.) to the output of your website.

There are multiple ways to prevent this, but the easiest is to use prepared statements. It looks something like this:

$stmt = $dbConnection->prepare("SELECT * FROM `main_img` WHERE `id`=?");
$stmt->bind_param('s', $id);
$stmt->execute();
$result = $stmt->get_result();
while($row = mysqli_fetch_assoc($query)) {
    // ...
}

This way you make sure MySQL doesn't interpret any user input as SQL code, but only as values.

Again, more in-depth information here: https://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.html

You did never output any image-data. You'll have to use readfile($imageData); to output the image

Here's an example for outputting images: Output an Image in PHP

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM