user3511194
user3511194

Reputation: 23

php image blob wont show

So I am trying to show an image from my mysql database. The image is saved as a blob format. I made seperate php file for fetching the image. I then call this file from where I want to show the image like so:

<img src="image.php?id=3" />

This is the file that fetches the image:

<?php
    require 'scripts/connect.php';

    if(isset($_GET['id']))
    {
        $id = mysql_real_escape_string($_GET['id']);
        $q = $db->prepare("SELECT image FROM products WHERE id = '$id'");
        $q->execute();
        $data = $q->fetch();

        header("content-type: image/jpeg");
        echo $data["image"];
    }
?>

But when I try and run this code no image shows up. Instead I get this annoying broken link image thing:

https://i.sstatic.net/LGGTF.png

Upvotes: 0

Views: 1335

Answers (3)

DonCallisto
DonCallisto

Reputation: 29912

Your code doesn't do what you expect.

Try to change

$q = $db->prepare("SELECT image FROM products WHERE id = '$id'");

in - if id field is numeric one; if isn't, add single quote -

$q = $db->prepare("SELECT image FROM products WHERE id = $id");

Your example didn't work as you were passing to query $id placeholder and not his value (you dind't concatenated it)

Of course with that method you're not save by SQL Injection at all, so you should use pepared statement that way

$q = $db->prepare("SELECT image FROM products WHERE id = :id");
$q->execute(Array(":id" => $id));

Edit

As OP told me that $data['image']; is a bitstream, I will suggest to use something like:

echo '<img src="data:image/jpg;base64,'. base64_encode($data['image']). '" alt='imagename'>;

or if your echo goes directly into src attribute:

echo 'data:image/jpg;base64,'. base64_encode($data['image'])

Upvotes: 1

Swaraj Giri
Swaraj Giri

Reputation: 4037

Try,

$query = $db->prepare("SELECT image FROM products WHERE id = :id");
$query->execute(array(":id" => $id));
$data = $q->fetch();

For serving the image, use

$mime = pathinfo($data['image'], PATHINFO_EXTENSION);
header('Content-Type: '.$mime);
ob_clean();
flush();
readfile($data['image']);

Note:

  • readfile() needs the image path to where the images are stored.
  • if you are use PHP >= 5.4, $query->execute([":id" => $id]); can be used instead of $query->execute(array(":id" => $id));

Upvotes: 0

Samuil Banti
Samuil Banti

Reputation: 1795

Try to replace

header("content-type: image/jpeg");

with

header("content-type: image/png");

Upvotes: 0

Related Questions