Page 1 of 1

How to store an image in DB and to print it back?

Posted: Thu Jun 06, 2002 8:09 am
by Sergiy
I've done this in PHP 4.06 (tested with PHP 4.04)

to put an image into DB i use the following code (assuming a user has apploaded an image via http post)

Code: Select all

...
$uf = $HTTP_POST_FILESї'img_file'];
$userfile_name = $ufї'name'];
$userfile_type = $ufї'type'];
if ($userfile_type == "" ){
	$userfile_type = "application/octet-stream";
}
$userfile_size = $ufї'size'];
$userfile_temp = $ufї'tmp_name'];

if($userfile_temp != "none" && $userfile_size != 0){
	$fd = fopen ("$userfile_temp", "rb");
	$file = addslashes(fread ($fd, filesize ("$userfile_temp")));
	fclose ($fd);
}
else {
	$file = "NULL";
}

$query = "INSERT INTO $ntable (id, img, type) VALUES (NULL, "$file","$userfile_type")";

$result = mysql_query ($query)
	or print "Query failed.\n";
...
to accsess an image I use the following html:

Code: Select all

<img src="image.php?id=1">
to print out an image i use this (image.php):

Code: Select all

$id = $HTTP_GET_VARS&#1111;"id"];
...
$query = "SELECT img, type FROM $ntable WHERE id="$id"";
$result = mysql_query ($query)
	or print "Query failed\n";

$line = mysql_fetch_array($result);
$file = $line&#1111;"img"];
$type = $line&#1111;"type"];
Header("Content-type: $type");
echo $file;
it works fine for PHP 4.06... but it doesn't work in PHP 4.2...

as i can see every NULL character (0x00) in output is converted to space (0x20)... and a GIF with all nulls converted to spaces is not looking as its author's expecting :lol:


:idea: Can anybody suggest a solution?
:?: Has anybody come into the same problem?
:) Can anybody try my code and say me i am not nuts?

yet another time ;)

Posted: Thu Jun 06, 2002 9:53 am
by Sergiy
:?: maybe someone can help with another way of storing and retrieving images to/from DB...

thanks in advance

Posted: Thu Jun 06, 2002 10:59 am
by mikeq
I assume you have looked at the post about register_globals, look at the sticky topic at the top of the PHP forum

Posted: Fri Jun 07, 2002 4:17 am
by Sergiy
mikeq wrote:I assume you have looked at the post about register_globals, look at the sticky topic at the top of the PHP forum
of course!

the matter is that an image is placed in my DB... But when it is printed back it is weird...

Posted: Fri Jun 07, 2002 6:16 am
by jason
This should help:

http://www.devnetwork.net/forums/viewto ... e+database

Amazing, the powers of search =)

Posted: Fri Jun 07, 2002 6:37 am
by volka
ah, yes, I still can recall it.
as mentioned he is only storing the url in the database.
Oh, well damn! Haha, I read "I am storing the image in the database", missing out on the 'url' part, haha.
sorry, jason - just kidding ;)


may be this one is helpful

Posted: Fri Jun 07, 2002 6:43 am
by jason
/me is just going to go hide in a hole :oops: ...and not post for a week as punishment.. I think I need a vacation :D