Storing Images in a database

Submitted by:Jhon Jhon

Date added:11 March, 2015

Category:PHP

PHP code shows how to upload images into a mysql database using

Tags: storing images , upload images

Code Snippet:

Creating the Image Database
First, create a mysql database called base64imgdb
(this is the name that will be used throughout the tutorial)
Second, create a table called images with two rows. Name the first one imgid, and give it the parameters
TYPE: INT EXTRA: auto_increment, and check the circle under Primary. Name the second sixfourdata, and make it
TYPE: LONGTEXT. Here is the sql code:

CREATE TABLE `images` (
`imgid` INT NOT NULL AUTO_INCREMENT ,
`sixfourdata` LONGTEXT NOT NULL ,
PRIMARY KEY ( `imgid` )
);
The READDIR.PHP script
This script reads a directory within the server, selects all the jpg and gif images, encodes them into base64, and uploads
them to the database, except in a different order. This is because the script reads each image in a loop, and we would
like to keep a constant connection to the mysql database instead of creating multiple ones. Here is the database
connection where username and password need to be changed:

<?PHP

$dbcnx = @MYSQL_CONNECT("localhost", "username",
"password");
IF (!$dbcnx) {
ECHO( "<p>connection to database server failed!</p>"
);
EXIT();
}
IF (! @MYSQL_SELECT_DB("base64imgdb") ) {
ECHO( "<p>Image Database Not Available!</p >" );
EXIT();
}
?>

Next we need to open the directory, where "./"is the directory the readdir.php file is located:

$path = "./";
$dir_handle = @opendir($path) or die("Unable to open directory $path");

This is the hardest part of the script: sorting the image types, reading the data using fopen, converting it using base64_encode,
and then inserting it into the table.

<?PHP

WHILE ($file = READDIR($dir_handle)) {
$filetyp = SUBSTR($file, -3);
IF ($filetyp == 'gif' OR $filetyp == 'jpg') {
$handle = FOPEN($path . "/" . $file,'r');
$file_content = FREAD($handle,FILESIZE($path . "/" . $file));
FCLOSE($handle);
$encoded = CHUNK_SPLIT(BASE64_ENCODE($file_content));
$sql = "INSERT INTO images SET sixfourdata='$encoded'";
@MYSQL_QUERY($sql);
}
}

?>

This is the last and final part of the readdir.php: closing the directory and stating the process is complete:

<?PHP

CLOSEDIR($dir_handle);
ECHO("complete");
?>

The Image Reader IMAGE.PHP
This file may be the hardest file to understand whenever you see how simple view.php is, but bear with me, your patience will pay
off. This file takes a request, requests the row in the table, decodes the data, and presents itself as an image. First, we have to connect to the database again:

<?PHP

$dbcnx = @MYSQL_CONNECT("localhost", "username",
"password");
IF (!$dbcnx) {
ECHO( "
connection to database server failed!
"
);
EXIT();
}
IF (! @MYSQL_SELECT_DB("base64imgdb") ) {
ECHO( "
Image Database Not Available!
" );
EXIT();
}
?>

Now we need to find out which row it's requesting, which is done using image.php?img=x:

<?PHP
$img = $_REQUEST["img"];
?>
After this, we need to connect to the table, get the data, and set it into variables:

<?PHP
$result = @MYSQL_QUERY("SELECT * FROM images WHERE imgid=" . $img .
"");
IF (!$result) {
ECHO("
Error performing query: " . MYSQL_ERROR()
. "
");
EXIT();
}
WHILE ( $row = MYSQL_FETCH_ARRAY($result) ) {
$imgid = $row["imgid"];
$encodeddata = $row["sixfourdata"];
}
?>

Now here is the last and most confusing part of the file:

<?PHP

ECHO BASE64_DECODE($encodeddata);

?>


Now let me explain this. All this does is decodes the base64-encoded image data, end echos it. That's it, nothing else.

VIEW.PHP (example viewer)
Okay, so you made it this far already. This is now the easiest to copy and paste but hardest part to understand, where
image.php?img=1 matches with whatever row the image is on, for example if it's row 357 then you would need to put

image.php?img=357:
<img src='image.php?img=1' border="0" alt="">

Now that wasn't so hard was it? But most of you are probably wondering why when you link to a page, you get an image. This
is the reason: images arent defined by their 3 letter suffixes (such as jpg or gif), but by how their headers are written.
IMAGE.PHP simply echos the image data, and acts like an image even though it just proccesses the request. This is why you get
an image.

readdir.php:
<?PHP

###############################
# DB CONNECTION
# CHANGE THESE VALUES
###############################
$dbcnx = @MYSQL_CONNECT("localhost", "username",
"password");
IF (!$dbcnx) {
ECHO( "
connection to database server failed!
"
);
EXIT();
}
IF (! @MYSQL_SELECT_DB("base64imgdb") ) {
ECHO( "
Image Database Not Available!
" );
EXIT();
}

$path = "./";
$dir_handle = @OPENDIR($path) or DIE("Unable to open directory $path");

WHILE ($file = READDIR($dir_handle)) {
$filetyp = SUBSTR($file, -3);
IF ($filetyp == 'gif' OR $filetyp == 'jpg') {
$handle = FOPEN($file,'r');
$file_content = FREAD($handle,FILESIZE($file));
FCLOSE($handle);
$encoded = CHUNK_SPLIT(BASE64_ENCODE($file_content));
$sql = "INSERT INTO images SET sixfourdata='$encoded'";
@MYSQL_QUERY($sql);
}
}

CLOSEDIR($dir_handle);
ECHO("complete");

?>


image.php:
<?PHP

$dbcnx = @MYSQL_CONNECT("localhost", "username",
"password");
IF (!$dbcnx) {
ECHO( "
connection to database server failed!
"
);
EXIT();
}
IF (! @MYSQL_SELECT_DB("base64imgdb") ) {
ECHO( "
Image Database Not Available!
" );
EXIT();
}

$img = $_REQUEST["img"];

$result = @MYSQL_QUERY("SELECT * FROM images WHERE imgid=" . $img .
"");
IF (!$result) {
ECHO("
Error performing query: " . MYSQL_ERROR()
. "
");
EXIT();
}
WHILE ( $row = MYSQL_FETCH_ARRAY($result) ) {
$imgid = $row["imgid"];
$encodeddata = $row["sixfourdata"];
}

ECHO BASE64_DECODE($encodeddata);
?>

view.php:
<html>
<body>
..
<img src='image.php?img=1' border="0" alt="">
..
</body>
</html>
 
 

Comments