I am trying to store images in a PostgreSQL database. I modeled the attempt on the PHPBuilder article by Florian Dittmer (http://www.phpbuilder.com/columns/florian19991014.php3). It's old and for MySQL but it's good. The code below is pretty close. Some binary is saved in the Postgres database. When trying to pull doesn't the image show up but the browser at least recognize it's an image (though put the pixel number extremely high). Help. I am not sure if I am screwing up saving the data or pulling it. Or both.
PHP for form to insert data (and display):
<?
$current_url = $_SERVER['PHP_SELF'];
?>
<html>
<head></head>
<body>
<h1>Image</h1>
<?
if ($_POST['action'] == 'fileupload') {
include("/web/php/erestaurant/db_back.inc");
$form_data = $_POST['form_data'];
$data = addslashes(fread(fopen($_FILES['form_data']['tmp_name'], "r"), $_FILES['form_data']['size']));
$file_type = pg_escape_string(fread(fopen($_FILES['form_data']['tmp_name'], "r"), $_FILES['form_data']['type']));
$add_image = pg_Exec($db_er, "INSERT INTO image (data, type) VALUES ('" . $data . "','" . $file_type . "')");
}
else {
// submit form
echo "<form action='$current_url' enctype='multipart/form-data' method='post'>";
echo "<input type='hidden' name='action' value='fileupload'>";
echo "<p>Suffix:<br><input type='text' name='textline' size='30'></p>";
echo "<p>Please specify a file, or a set of files:<br><input type='file' name='form_data'></p>";
echo "<p><input type='submit' value='Send'></p></form>";
// display all pics
include("/web/php/erestaurant/db_front.inc");
$test = pg_Exec($db_er, "select * from image");
for ($t=0; $t < pg_NumRows($test); $t++) {
echo "<img src='get_binary.php?id=$t'>";
}
}
?>
</body>
</html>
get_binary.php
<?
$id = $_GET['id'];
if ($id) {
// you may have to modify login information for your database server:
include("/web/php/erestaurant/db_front.inc");
$image = pg_Exec($db_er, "select * from image where image = $id");
$data = pg_unescape_bytea(pg_Result($image,0,data));
// Header( "Content-type: $type");
Header("Content-type: image/gif\n\n");
// header("Content-length: $size);
// header("X-Image-ID: $data);
echo $data;
}
?>
You can check out the get_binary.php file on a live system: http://esystems.us/get_binary.php?id=10
I tried some variations on $data cleanup in get_binary.php, the example above use pg_unescape_bytea but I also tried strip backslash and clean.
Another minor snag, I don't get the filetype to work correctly but work around that by hardcoding content type and only upload gifs.
The data column holding the binary data in Postgres is of the type bytea.