Forum Moderators: coopster

Message Too Old, No Replies

Problem displaying image from database

php mysql database

         

netlander

4:36 am on Sep 22, 2007 (gmt 0)

10+ Year Member



Hello webmasters.A new member.
I used the code below to pull out an image from a mysql database
but nothing shows on the page and there was no error message to
indicate any problem.What could be wrong.The image is actually in the
database with all the details:

<?php
if(isset($_GET[loginid]))
{
$con=mysql_connect("localhost","name","pass");
if(!$con)
{
die('Could not connect to database:'.mysql_error());
}
mysql_select_db("datab",$con);
$id = $_GET[loginid];

$query = "SELECT name, type, size, content " .
"FROM image WHERE id= '$id'";

$result = mysql_query($query) or die('Error, query failed');
$file=mysql_fetch_array($result);
$name=$file['name'];
$type=$file['type'];
$content=$file['content'];

header('Content-length: '.strlen($content));
header("Content-type: $type");
header("Content-Disposition: inline; filename=$name");
echo $content;

}
mysql_close($con)
?>

Thank you.

mattbyrnes

5:46 am on Sep 22, 2007 (gmt 0)

10+ Year Member



It may be how you are storing the image in the database.

It might be helpful to debug it if you post the code that stores the image.

You need to make the image database safe using base64_encode() and addslashes() before storing it. There are a few user comments about how to store images in the db here: [php.net...]

When you pull the image out, you pass the image to base64_decode(). (And stripslashes() if it doesn't happen automatically).

That may be a start.

I'm having trouble as well with a similar problem.

netlander

7:22 pm on Sep 23, 2007 (gmt 0)

10+ Year Member



Thanks.Here is the code that i used to store the image.

<?php
$id=$_GET[id];
if(isset($_POST[upload]))
{
$fileName = $_FILES['userfile']['name'];
$tmpName = $_FILES['userfile']['tmp_name'];
$fileSize = $_FILES['userfile']['size'];
$fileType = $_FILES['userfile']['type'];
$imageInfo = getimagesize($tmpName);
$src_width = $imageInfo[0];
$src_height = $imageInfo[1];
$src_img = imagecreatefromjpeg($tmpName);
$dst_img = imagecreate(100,100);
imagecopyresized($dst_img, $src_img, 0, 0, 0, 0, 100, 100, $src_width, $src_height);
imagejpeg($dst_img,$tmpName);
$fileSize = filesize($tmpName);

$fp = fopen($tmpName, 'r');
$content = fread($fp, $fileSize);
$content = addslashes($content);
fclose($fp);
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
}
$con=mysql_connect("localhost","db","pass");
if(!$con)
{
die('Could not connect to database:'.mysql_error());
}
mysql_select_db("db",$con);
$query = "INSERT INTO image (name, size, type, content,id ) ".
"VALUES ('$fileName', '$fileSize', '$fileType', '$content','$id')";
mysql_query($query) or die('Error, unable to upload ');
$_SESSION['authorized'] = TRUE;
header("Location:uploadsuccess.php?loginid=$id");
}
mysql_close($con)
?>