• Home

Logo

Navigation
  • Home
  • Articles
    • Content Writing
    • Design
    • General
    • Internet Marketing
    • Social Media
    • Tools and Tips
    • Usability
    • Web Hosting Articles
  • Tutorials
    • AJAX Tutorials
    • ASP Tutorials
    • C# Tutorials
    • CGI and Perl Tutorials
    • CSS Tutorials
    • Flash Tutorials
    • HTML Tutorials
    • Illustrator Tutorials
    • Java Tutorials
    • JavaScript Tutorials
    • Linux Tutorials
    • Miscellaneous Tutorials
    • MySQL Tutorials
    • Photoshop Tutorials
    • PHP Tutorials
    • Python Tutorials
    • Wireless Tutorials
    • WordPress Tutorials
    • XML Tutorials
  • Scripts
    • AJAX Scripts
    • ASP Scripts
    • ASP.NET Scripts
    • CGI & Perl Scripts
    • Flash Scripts
    • Java Scripts
    • JavaScript Scripts
    • PHP Scripts
    • Python Scripts
    • Remotely Hosted
    • Tools and Utilities
    • XML Scripts
  • Answers
  • Online Services
  • Tools

Storing Images in a Database

By Darren W. Hedlund | on Jun 21, 2005 | 0 Comment
MySQL Tutorials PHP Tutorials
  • Tweet
  • Share
  • Tweet
  • Share

Storing Images in a Database

This tutorial teaches you how to upload images into a MySQL database using PHP. Even though it sounds complicated, it is fairly simple and has many practical applications. One example of an application would be Forum User Images. Take user avatars for example. Its impractical to upload avatar files to one common folder, because chances are sooner or later two users will have the same name for an avatar, and either one avatar will be overwritten, or the other not accepted, causing trouble. Image Databasing solves this problem by inserting the image data into its own unique row in a table, each assigned with an ID number instead of a filename. Images can then be called from the database and be view using one PHP file for all images. How are they inserted into the database? By converting the data to base64. If you’re confused, please bear with me, you will understand it soon.

There will be 3 PHP files in this tutorial:

readdir.php – this puts all the images in a folder into the database
image.php – the actual image script that displays the imag
view.php – an example file that shows you how to call the image
Base 64 is an encoding for binary data as described as a means of encoding email bodies in the IETF’s MIME RFC. Base64 consists only of 64 encoding characters (A-Z, a-z, 0-9, +, /) that are a subset of US-ASCII. You can find out more here.

PHP includes 2 base64 functions – base64_decode() and base64_encode(). You can find out more about each one here and here respectively.

Creating the Image Database

First, create a MySQL database called base64imgdb (this is the name that will be used throughout the tutorial). Alternatively, you can use an existing database and just add the tables.

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 you can execute to create the table:

constant connection to the MySQL database instead of creating multiple ones. Here is the PHP code, you will need to change the username and password parts:

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

readdir.php file is located:

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.

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 proccess is complete:

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:

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 its requesting, which is done using image.php?img=x

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:

base64_decode($encodeddata);
?>

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

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 its row 357 then you would need to put image.php?img=357:

readdir.php

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

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>

Share this story:
  • tweet

Author Description

Darren Hedlund is a freelance Web developer, writer, and data analyst. Darren has a degree in Computer Information Science and has spent the last 15 years developing application and environments from hand held, windows, web, virtual science, gaming, artificial intelligence and graphics design.

Darren's coding knowledge ranges from C+, Visual Basic, .NET, PHP, JSP, REXX, KIXX, and many others. His graphical and environmental knowledge stems in Macromedia Flash, 3D studio Max, Curious Labs Poser, Adobe Photoshop, and many others. Darren works in many platforms ranging from database, visual design, and, system development.

No Responses to “Storing Images in a Database”

You must be logged in to post a comment.

Connect With Us

RSSSubscribe 1,241Followers 494Likes
  • Popular
  • Recent
  • Comments
  • Creating Energy Spheres in Photoshop

    Apr 15, 2008 - 96 Comments
  • Easy Screen Scraping in PHP with the Simple HTML DOM Library

    Aug 6, 2008 - 20 Comments
  • Calculating date difference more precisely in PHP

    Mar 7, 2008 - 13 Comments
  • When Does Hosting Your Website in the Cloud Make Sense?

    Oct 8, 2010 - 2 Comments
  • Fun with the Microsoft Managed Extensibility Framework Part 2

    Oct 6, 2010 - 0 Comment
  • Fun with the Microsoft Managed Extensibility Framework Part 1

    Sep 22, 2010 - 0 Comment
  • Website Management on the go with the iPad

    I appreciated your post, but I was looking for something I didn't...
    November 24, 2012 - drmoderator
  • Creating Energy Spheres in Photoshop

    I'm a little stuck down here especially at the step of creating the...
    November 23, 2012 - sarah
  • Running background processes in PHP

    Can you give an example? As see it, you can use this only when you...
    November 16, 2012 - Shaked Klein Orbach
Developer Resources
  • Tutorial Directory
  • Learn HTML
  • Learn PHP
  • Learn CSS
  • Learn AJAX
  • Learn JavaScript
  • Learn Pear
  • White Papers
  • Resources
    • NetVisits Web Directory
    • Realtor Pixels
    • Answers On The Run
    • Ask A Geek
  • Recent Posts

    • When Does Hosting Your Website in the Cloud Make Sense?
    • Fun with the Microsoft Managed Extensibility Framework Part 2
    • Fun with the Microsoft Managed Extensibility Framework Part 1
    • Website Management on the go with the iPad
    • Code Contracts in C# 4.0 – Part 1

    Calendar

    May 2013
    M T W T F S S
    « Oct    
     12345
    6789101112
    13141516171819
    20212223242526
    2728293031  

    Recent Comments

    • drmoderator on Website Management on the go with the iPad
    • sarah on Creating Energy Spheres in Photoshop
    • Shaked Klein Orbach on Running background processes in PHP
    • Thomas Cuvillier on How To Upload Files Using PHP
    • rizal aditya on Extracting text from Word Documents via PHP and COM
    • Home
    © 2003 - 2013 DeveloperTutorials.com. All Rights Reserved. Privacy Policy.