7

I store images in my mysql database as blob. I can load these files with a query in a variable, but how can I send back the contents of this variable to the browser as an image?

Can the html file contain something like this <img src="smtg.png"> ? Or how the request can be made?

2 Answers 2

7

You need a script that echos out the image data. Use header() to set the appropriate content type, and then echo the data. For example:

header("Content-type: image/png");
...
echo $db_results['imgdata'];

Then, call your script from the HTML page like this:

<img src="yourimagescript.php" />

Ideally, you should be storing file type in a column next to your image data, so you can dynamically set the correct content type.

Sign up to request clarification or add additional context in comments.

Comments

2

PHP

<?php
mysql_connect("localhost","test","test");
mysql_select_db("test");
$imageid = (int)$_GET['imgid'];
$rs = mysql_query("select * from images where imageid=$imageid");
$row = mysql_fetch_assoc($rs);
$imagebytes = $row['imgdata'];
header("Content-type: image/jpeg");
print $imagebytes;
?>

HTML

<img src="location_to_your_php_script.php?imgid=21" alt="xxx" />

5 Comments

Of course you need to change the mime type according to your image.
Even though you are casting the $_GET parameter to an int, it is worth escaping the data so that folks who don't know go and copy and paste this and open themselves up to SQL injection.
Thank you! I also wrote my code by Brad's post, but your solution is good to. Thank you very much for your effort!
@Senad, what about your int? What does this do? It isn't just a simple cast? Does something happen in the background? Like escaping or something like this?
when casting to int, than sql injection from url wont be applied to variable e.g. $int = (int)"' truncate table users"; will be 0 so no problems with the sql injection.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.