Reading an Image file from a mysql database using php - php

I am trying to display an image, but my webpage displays encoding stuff instead. Below is my code:
<?php ob_start();?>
// html markups goes here
<?php include 'login.php';
if(isset($_GET['productid'])){
$productid = $_GET['productid'];
$sql = "select tyre_image from tyres where product_id = '$productid'";
$result = mysql_query($sql) or die(mysql_error());
header("Content-type :image/jpg");
echo mysql_result($result,0);
}
ob_end_flush();
?>
I am using $_GET associative array($_GET['variable']) to get the product ID via a link on another page.
How would I fix this?

I had no idea the Content-type header was this picky, but change the spacing around the colon (and also image/jpg should be image/jpeg):
header("Content-type: image/jpeg");
Per the answer below, I agree - this fix assumes that this script is just used for displaying an image in your HTML, ala <img src="path/to/your/image.php?productid=123" />.
Further light reading on the image/jpeg MIME type spec here.

Related

php - set photo to image by path [duplicate]

This question already has answers here:
Output an Image in PHP
(12 answers)
Closed 4 years ago.
Well, my page contains an img like this:
<img id=".."class=".." src="setPhoto/second_photo.php">
Now, as you can see in src I have put a .php file:
<?php
$id = $_SESSION['u_id'];
$sql = "SELECT * FROM users WHERE id=$id";
$result = mysql_query("$sql");
if ($row = mysqli_fetch_assoc($result)) {
mysql_close($link);
header("Content-type: image/jpeg");
echo $row['profile_front_photo'];
} else {
// no result from database
mysql_close($link);
header("Content-type: image/jpeg");
echo '../../../_images/default.jpg'; //Here is the promblem
}
?>
This code with the path, is not working. I want to set a photo to img by using a path.
Is it possible?
The browser asked for an image. Instead of getting an image back, it got back a string "../../../_images/default.jpg".
Instead, you want to open that file and pass its contents through. You also need to set the correct MIME type in the response.
You should be able to find simple tutorials for this online, or take a look at e.g. https://secure.php.net/manual/en/function.fpassthru.php
You can try this:
dirname(__FILE__)
it will get the root folder your project and then you specified your path like this
dirname(__FILE__). '/imagefoldername/_images/default.jpg';
Make it
$path='../../../_images/default.jpg';
echo "<img src='.$path.'>";

PHP - images stored as BLOB displayed as broken links

I'm working on a store application in PHP and am having trouble displaying stored on MySQL database. I'm storing the images as medium BLOB type and I'm confident that the images are properly formatted during and after being uploaded to the database. (I can download the images from the database directly and view them as jpeg images).
But if I try to display my images in the web page, I am getting the broken image icon. The only way I've been able to get the picture to display from sql is by using base64 encoding, but that's not the method I want to use.
Here is my code. It fetches all the products from the database and displays their id, description, and image in a table row.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<title>Image Test</title>
<body>
<?php
include("mylibrary/login.php");
login();
$query = "SELECT prodid, description FROM products";
$result = mysql_query($query) or die(mysql_error());
echo "<table width=\"50%\" cellpadding=\"1\" border=\"1\">\n";
echo "<tr><td>Product ID</td><td>Description</td><td>Image</td></tr>\n";
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$prodid = $row['prodid'];
$description = $row['description'];
echo "<tr><td>$prodid</td><td>$description</td>\n";
echo "<td><img src=\"showimage.php?id=$prodid\" width=\"80\" height=\"60\"></td></tr>\n";
}
echo "</table>\n";
?>
</body>
</html>
This is the showimage.php code. The showimage.php file is only showing a broken image. I've looked at the raw data of the images and they're all formatted correctly. :
<?php
//header('Content-Type: image/jpeg');
$prodid = $_GET['id'];
$con = mysql_connect("localhost", "test", "test") or die('');
mysql_select_db("store", $con);
$query = "SELECT picture from products WHERE prodid=$prodid";
$result = mysql_query($query);
$row = mysql_fetch_array($result, MYSQL_ASSOC);
$picture = $row['picture'];
header("Content-type: image/jpeg");
echo $picture;
?>
I'd really appreciate help in understanding why this code isn't working. I've read numerous articles on this site and from google searches and they all say that this code should work.
As a side note, I don't want to use the base64 encoding method because I'm taking a class and this is the method that we're using (I'm also the only person who is having this problem).
Generally, the code looks almost okay. The problem with pictures is, it has to be exactly correct, otherwise it cannot be correctly displayed. Try the following things:
Use "Content-Type: image/jpeg instead of "Content-type: image/jpeg"
Remove the closing tags ?> in showimage.php - if there is a space after the closing tags, that could be your problem. You should never use closing tags for PHP-only files.
If that does not help, remove the header for the content type and have a look at what is actually returned to you by calling the picture url and compare the data to the original image. That way you can confirm that the picture data is correct or what the differences are.

Displaying images stored in a database using PHP

For my current assignment I'm trying to store files into the DB and display them. Currently I have no problem storing the files but I can't display them properly. I'm using this in my main form.
<td><a href=getImage.php?id='.$file[0].'" />Resume</a></td>
And this is the query I'm using to get the file out of the DB.
$sql = "SELECT file FROM table WHERE Res_ID=$referenced_ID";
$result = mysqli_query($dbc, $sql);
$row = mysqli_fetch_assoc($result);
header('Content-type: image/jpg');
echo "<img src=\"{$row['file']}\" /><br />";
The result is
…³V!µÔ¢ošweöÿZ–îÌèEÈÎpEJ·˜kä€òþòâ­Gas
È*G¨¥vA¤uEN¤S]‰:ñY“iwØ8‡¥e]ØÝGÑ‘øQÍ!«3¨ÄvÙÁu§]zÕÿOã^ssÌuáY7WP“ÔT6Æà™ëâþÊQË!üi­oe8
9ô5ã?ÛSÇÔ‘RÃ⛘VCBh¹>ϳ=BïÃVwåçÔW#¯|8†ufŠ4ob1PiÞ=q(,>µÐYx®Æ÷¥ò›Ñ5b½äy6«ðÆbͲϡ®fóá–
í„ξ‹’xvîYVEöæ«6§]|²½ýj‡Ï#åËßjv™-k.u\ŠÈ›O–#ó!ЊúÊmcLþ-¹ïšÆÔ4ïkùñE¸ÿ0h±j§‘òù
Ԉ켯íº×ÂÝã/g:»¸âïþ=³-²û?áHÑI3ŒKÙW¨ÍNºŽî-¶_Ã#IÙ¸{Tiû¸>â€3ÿu7#V[àü­š‘í•ùT[9\Ó’ª?oçJ©ù…69Ùxß÷¹©ö¼
|ÊOµ°™W##êàÔ²iw®»–uõ5Eíåˆà«ôÅHä¯"‘\PˆÙŽ>ïÖœÖò'¡÷†^Ž#3Sg+ÀéYžt±uBG­>=H'ÞB>”À¾7ƒè)É#)åsU×S‰‡R>µ"\£ô4‹é"ç=D/ÿ-
š¦¼ô©àuCó'´‰ Ë7çPëÑ¿Z½åÛÌ>\Mk
&ʱœÒ0ê*#)ÏAV怩#Bd`^):ܲ¯ü*îÛERk†^ù¦CiÃsõ¦
ší¹Îj¬“*øhf﶑¬†CqíH’ëëIæsŒŠÐ{=ÍW{
:dÓ¸aÐœýjXîæCÃA:æ”CŽÿe5iG£}h7I7ßCüê¬8èqP–t<Ò…©£¸MÄúbª¼EM'ÚJš‘oPýôϽHˆ2GµZ¶¾T
H/Ò¢yb“§ò¦R9ÓC6,n...
I'm using images as a sample at the moment but the finished php should eventually allow to display PDF documents. If it's any help I'm using phpmyadmin and MySQLi.
As the comments suggest, storing the file location in the database is much better than storing the file's data in the database. BUT if you need to store the file contents in the database for some reason, there are two methods. One is using the HTML data: URL and the other is having a PHP file as the middle man.
For the PHP Middle Man method, look at the answer above mine where it sets the header information and then echo's the file contents. The file extension doesn't matter since browsers refer to the content-type header instead of file extensions.
For the Data URL method, which can be placed directly in your code easily check out http://en.wikipedia.org/wiki/Data_URI_scheme
<?php
// Array of valid Mime Types, prevents possible XSS methods.
$valid_mimes = array(
'image/png',
'image/gif',
'image/jpeg'
);
// Obtain Mime Type using finfo
// Finfo allows for strings instead of file path
$finfo = new finfo(FILEINFO_MIME_TYPE);
$mime = $finfo->buffer($row['file']);
// Check if mime is in our $valid_mimes array
if(!in_array($mime,$valid_mimes)) {
// Handle Error
echo 'Illegal Mime Type: '.$mime;
die();
}
$b64 = base64_encode($row['file']);
echo '<img src="data:'.$mime.';base64,'.$b64.'" />';
?>
You cant output <img src=\ as an output it will corrupt the image file and
Please use getImage.php as a different file to output images or verify that no output is printed before,after or in mid of image else it will corrupt the image.
if(isset($_GET['id'])){
$sql = "SELECT file FROM table WHERE Res_ID=$referenced_ID";
$result = mysqli_query($dbc, $sql);
$row = mysqli_fetch_assoc($result);
header('Content-type: image/jpg');
echo $row['file'];
}

PHP display image from Database(medium blob)

I currently have a database where i can store images in..
But the PHP page i created to display them... doesnt work.
But when i use the link as scr for a < img> it shows a empty image frame.
if i echo the image directly, i get a lot of strange signs
the way i want to display the images is:
< img src="image.php?image="'.$imageID.'/>
the code i use for displaying the image(image.php) is:
<?php session_start();
if(!isset($_GET['image']))
{
header("HTTP/1.0 404 Not Found");
}
else{
$link = mysql_connect('localhost', '45345345435435345', 'wewfsersdfds');
if (!$link) {
echo "error";
die;
}
$db_selected = mysql_select_db(Tha base, $link);
if (!$db_selected) {
echo "error";
die;
}
$nummer=(int)trim(stripslashes($_GET['image']));
$mynr=$nummer;
$sql="SELECT * FROM Foto WHERE fotonr=$mynr";
$result=mysql_query($sql);
if(!$result)
{
echo "error".mysql_error();
header("HTTP/1.0 404 Not Found");
}
else
{
$foto = mysql_fetch_assoc($result);
header("Content-type: ".$foto['type']);
echo $foto['image'];
}
}
?>
I tried a lot already but it wont work :(
i updated the code to the newest version.
Made mistakes with the sql(selected nothing/never do mysql_real_escape_string of a int)
Now it shows a straight line of characters, instead of an image, thats at least a improvement...
Can someone help me?
Thanx for your time!
Honestly, I know it can be tricky. I think it has to do with how your storing it, not how your outputting it. I have one example of storage from a recent project I can show.
$fp = fopen($image_path, 'r');
$image = fread($fp, filesize($image_path));
$image = addslashes($image);
fclose($fp);
// save $image into DB.
Not sure if you do similar with file_get_contents. How I output is similar to how you are doing it, only I use a ORM and a framework.
I suspect that your problem is in your conversion - perhaps between strings and images, or perhaps between the different image formats.
Have you tried saving the image gotten through image.php, and comparing the binary against the known-good image file? Perhaps once you do that, the answer will be apparent (e.g. wrong length, corrupted header, etc.)
You may want to consider a different database record. Most db's support storage of binary blob data, which you could more simply return. This would be simpler (and take less space in your db!) than using the php functions to stringify and imagecreatefromstring.
Also, I believe that you're attempting to use imagegif, imagejpeg, imaging to perform image format conversion for you. This isn't how I understand them to work, based on my reading at: http://php.net/manual/en/function.imagecreatefromstring.php. Try storing and retrieving the same format to tease out whether this is your problem.
Try looking at Content-type. I think it's case sensitive. Try Content-Type.
http://en.wikipedia.org/wiki/List_of_HTTP_header_fields
$sql = "SELECT * FROM Foto WHERE fotonr=$mynr";
$result = $conn -> query($sql);
while ($row = $result -> fetch_assoc()) {
$img= '<img src="data:image/jpeg;base64,'.base64_encode( $row['image'] ).'" width=350px0px height=300px/>';
}
echo $img;

Create/display image from dataURL

is it possible to create and display a picture file from dataURL received by POST?
Something like:
<?
$imgstr = $_POST["imgdata"]; //data:image/png;base64,.... etc (it's always PNG)
echo base64_decode($imgstr); // idk what this really does
?>
I can't use <img> tag to display it. It needs to act like a "normal" image file.
Yes, try:
<img alt="Base64 Image" src="data:image/png;base64,{$imgstr}" />
Edit: make sure you clean up your $_POST, so people do not insert dangerous junk...
If e.g. your input is
// Red dot graphic, stolen from Wikipedia
$imgstr = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==';
Then you can do what you want with
// Grab the MIME type and the data with a regex for convenience
if (!preg_match('/data:([^;]*);base64,(.*)/', $imgstr, $matches)) {
die("error");
}
// Decode the data
$content = base64_decode($matches[2]);
// Output the correct HTTP headers (may add more if you require them)
header('Content-Type: '.$matches[1]);
header('Content-Length: '.strlen($content));
// Output the actual image data
echo $content;
die;
You must set correct header before echo.
header( 'Content-Type: image/jpeg' );

Categories