Jump to content

Getting image from MySQL (blob).


Zebramoose

Recommended Posts

Hi!

 

I am building a little PHP/MySQL application where pictures are uploaded and stored in MySQL in a longblob. These are special circumstances and storing images in the database in an absolute must.

 

Uploading is working fine. The upload script inserts the following into the field `image_data`:

base64_encode(file_get_contents($_FILES['image']['tmp_name']))

 

The problem is displaying the images. I cannot for the life of me make it work. I've tried the code on multiple systems with various versions of PHP and MySQL.

 

I have two files: one called view.php and one called show.php.

 

# view.php
# It gets $info['id'] from a query getting the ID of the recent-most image uploaded. 

echo '<img src="show.php?id='.$info['id'].'" alt="" />';

 

# show.php
# $id is determined by $_GET['id'] and passes through security checks I've omitted here.
# There is zero (not even a whitespace) output before the header()s are sent.

$query = "SELECT `image_data`,`image_mime`,`image_size` FROM `upload`.`files` WHERE `id` = '$id';";

$sql = mysql_query($query) or die(mysql_error());

$image = mysql_fetch_assoc($sql);

header('Content-Type: ' . $image['image_mime']);
header('Content-Length: ' . $image['image_size']);

echo base64_decode($image['image_data']);

 

The problem is that no image is displayed either in view.php or when I call show.php directly with a valid ID. I have verified that $image['image_mime'] and $image['image_size'] contain the right data.

 

However, if I download show.php and change extension to for example .jpg, the image is there. So the image is stored correctly in the database and $image['image_data'] is outputting the right data.

 

I even compared checksums for the image before and after and they're identical, so I would conclude that the error is in the outputting of the image - but I can't figure out what.

 

Error_report is set to E_ALL but there's nothing useful coming out.

 

Any ideas?

Link to comment
https://forums.phpfreaks.com/topic/227299-getting-image-from-mysql-blob/
Share on other sites

<?PHP
$FIND = mysql_query("SELECT * FROM imagedata WHERE imagecode = '$DO' && imagemodel = '$WHAT'") or die(mysql_error());
$FOUND = mysql_fetch_array($FIND);
header("Content-type: image/".$FOUND['imagemime']);
echo $FOUND['imageraw'];
?>

 

This is mine and it's working nicely. Try use the example.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.