I'm having an interesting problem. I'm trying (unsuccessfully) to store an image in a BLOB, and then retrieve it for display later. My image seems to store just fine, but when I retrieve it, I get a broken image (red x in IE, missing image icon in netscape). I hope someone can shed some light on what I am doing wrong.
Here's upload.php:
<html>
<head><title>File Upload To Database</title></head>
<body>
<form enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input name="userfile" type="file" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
<?php
if(!isset($_FILES['userfile'])) {
echo '<p>Please select a file</p>';
}
else {
upload();
}
// the upload function
function upload(){
require ("config.php");
$dbhandle = mysql_connect($DBHOST, $DBUSER, $DBPASS) or die ("Could not connect: ".mysql_error());
mysql_select_db($DBNAME, $dbhandle) or die(mysql_error());
$file = fopen($_FILES['userfile']['tmp_name'], "r");
$imgData = addslashes(fread($file, filesize($_FILES['userfile']['tmp_name'])));
$size = getimagesize($_FILES['userfile']['tmp_name']);
$sql = "INSERT INTO images ( image_id, image_type, image, image_size, image_name) VALUES ('', '{$size['mime']}', '{$imgData}', '{$size[3]}', '{$_FILES['userfile']['name']}')";
if (mysql_query($sql)) {
echo 'File Uploaded!';
}
}
?>
And here's the view.php:
<?php
if(isset($_GET['image_id'])) {
require ("config.php");
$dbhandle = mysql_connect($DBHOST, $DBUSER, $DBPASS) or die ("Could not connect: ".mysql_error());
mysql_select_db($DBNAME, $dbhandle) or die(mysql_error());
$sql = "SELECT image, image_type FROM images WHERE image_id='".$_GET['image_id']."'";
$result = mysql_query("$sql") or die("Invalid query: " . mysql_error());
$type = mysql_result($result, 0, 'image_type');
$data = mysql_result($result, 0, 'image');
header("Content-type: " . $type);
echo $data;
}
?>
I know this isn't rocket science - but for some reason it isn't working. When I view the DB in phpmyadmin, I can see the data is inserted properly. I made a copy of view.php and simply outputted a strlen($data), and I get the correct number of characters as I expect from the BLOB.
The image type is also correct (echo $type; reveals 'image/jpg' or 'image/gif' - sans quotes, depending on what I upload), but when I browse to view.php?image_id=N (where N is a number corresponding to an uploaded image), I get a broken image.
What am I doing wrong? Is the data getting munged when I insert it?