1

i need to display an image from my php database. I know that the image is there and this should work could anyone tell me why it is not working? also i know that i am successfully connecting to the db so that is not the problem

here is page one index.php after i connected to the database

<?php
$query = mysql_query("SELECT * FROM data WHERE id= 1");    
while($data=mysql_fetch_array){
?>
<p> <?php echo $data['title']; ?></p>
<img src="img.php?id=1"/>    
<?php } ?>

and here is img.php

<?php
$id=$_GET['id'];
$query = mysql_query("SELECT * FROM data WHERE id= $id");
while($data= mysql_fetch_array($query)){
$image=$data['image'];
header("content-type: image/jpeg");
echo $image;
}
?>

i have been trying to find the answer to this for hours

  • 2
    echo the query to see what is going on. Also try to run the `echo`ed query directly. Also please stop [introducing SQL injection](http://stackoverflow.com/questions/60174/how-to-prevent-sql-injection-in-php) vulnerabilities in your applications. Also please start indenting your code. – PeeHaa Jun 15 '13 at 15:16
  • i echoed the $data['image'] directly and it gave me the char sheet could injections be my problem or is it the GET method? – user2489017 Jun 15 '13 at 15:26
  • 1
    It is not the problem you want to solve in your question, but it is a far more important / troublesome problem. – PeeHaa Jun 15 '13 at 15:28

2 Answers2

0

You need to create an image data resource instead of echo $image;

$img=false;

if($img=@imagecreatefromstring($data['image'])){

   header('Accept-Ranges: bytes');
   header('Content-Type: image/jpeg');      
   imagejpeg($img);
   imagedestroy($img);

}
else{

   //error message

}
RafaSashi
  • 16,483
  • 8
  • 84
  • 94
  • @user2489017 use mysqli functions intead of mysql for a better safety in your applications – RafaSashi Jun 15 '13 at 15:27
  • @echo_Samir the base64 solution is not compatible with every browsers. Your second option is a good alternative but doesn't solve the blob issue. – RafaSashi Jun 15 '13 at 15:40
0

You can convert the image data into base64 and stick it in an tag.

   echo '<img src="data:image/jpeg;base64,' . base64_encode( $data['image'] ) . '" />';
  • Or other best solution is to store image as by its name only, not blob.

then call the image like that

<img src="<?php echo $data['image_name_in_database'].'gif' ;?>"  height="42" width="42">

this link may help you

Community
  • 1
  • 1
echo_Me
  • 37,078
  • 5
  • 58
  • 78