Ok, here it is... in all its glory. The final working version.
First, my image database is formed by two different tables. One table contains the filename, filesize, filetype, a description, and a key to reference this image by. The other table stores that image_id, a file_id, and the actual image data. The file_id is used so that images can be chopped up into smaller bits when inserted into the database. This is nice because some DB servers limit how large data packets can be.
So here is the function I used to put images into the DB:
Code: Select all
function add_image($article_id, $description, $file) {
$db = DB::connect(CMS_DSN);
if (DB::isError($db))
die ($db->getMessage());
if ($file['size'] > MAX_FILE_SIZE) {
return "ERROR: File is larger than max allowed.";
}
$sql = "INSERT INTO cms_images (article_id, description, filename, filesize, filetype)
VALUES ('" . $article_id . "', '" . $description . "', '" . $file['name'] . "', '" . $file['size'] . "', '" . $file['type'] . "')";
$result = $db->query($sql);
if (DB::isError($result))
die ($result->getMessage());
$id = mysql_insert_id($db->connection);
$fp = fopen($file['tmp_name'],"r");
while (!feof($fp)){
$data = base64_encode(fread($fp, MAX_SQL));
$sql = "INSERT INTO cms_imagedata (image_id, data)
VALUES ('" . $id . "', '" . $data . "')";
$result = $db->query($sql);
if (DB::isError($result))
die ($result->getMessage());
}
fclose($fp);
$db->disconnect();
}
Now to view the images, I put the following in a HTML file:
Code: Select all
<img src="a/path/to/image.php?id=??">
And image.php looks like this:
Code: Select all
require_once('DB.php');
require_once('db_connections.php');
$fetchmode = DB_FETCHMODE_ASSOC;
$images = array();
$image_id = isset($HTTP_GET_VARS['id']) ? $HTTP_GET_VARS['id'] : NULL;
$db = DB::connect(CMS_DSN);
if (DB::isError($db))
die ($db->getMessage());
$sql = "SELECT data
FROM cms_imagedata
WHERE image_id = '" . $image_id . "'
ORDER BY file_id DESC";
$result = $db->query($sql);
if (DB::isError($result))
die ($result->getMessage());
while ($row = $result->fetchRow($fetchmode)) {
$images['filedata'] .= $row['data'];
}
$sql = "SELECT filetype
FROM cms_images
WHERE image_id = '" . $image_id . "'";
if (is_array($row = $db->getRow($sql)))
list($filetype) = $row;
$db->disconnect();
ob_end_clean();
ob_start();
header("Content-type: " . $filetype);
header( "Content-Disposition: inline");
echo base64_decode($images['filedata']);
And thats it!