Get your catchy domain at

Upload Image to Mysql Database with PHP

Dynadot Dynadot
Hi, this is my first tutorial. I have tested it and it all works great.
It should work with any type of image.

Today, err.. class, were going to make an image >> database uploader.

-Basic knowledge of php and mysql.
-Access to a mysql database.

First of all, create a table (and a database if necessary):

CREATE TABLE `images` (
PRIMARY KEY ( `img` )

Secondly, create a directory called "temporary" and chmod it to 777.

Ok, now that you have made the table and directory lets get to the coding.
This script will consist of 2 pages, "upload.php" and "image.php".

First page, "upload.php":

//connect to database. Username and password need to be changed
mysql_connect("localhost", "username", "password");

//Select database, database_name needs to be changed

if (!$_POST['uploaded']){
//If nothing has been uploaded display the form

<form action="<? echo $_SERVER['PHP_SELF']; ?>" method="post" 
<input type="file" name="image"><br><br>
<input type="hidden" name="uploaded" value="1">
<input type="submit" value="Upload">

//if the form hasn't been submitted then:

//from here onwards, we are copying the file to the directory you made earlier, so it can then be moved 
//into the database. The image is named after the persons IP address until it gets moved into the database

//get users IP

//don't continue if an image hasn't been uploaded
if (!empty($image)){

//copy the image to directory
copy($image, "./temporary/".$ip."");

//open the copied image, ready to encode into text to go into the database
$filename1 = "./temporary/".$REMOTE_ADDR;
$fp1 = fopen($filename1, "r");

//record the image contents into a variable
$contents1 = fread($fp1, filesize($filename1));

//close the file

//encode the image into text
$encoded = chunk_split(base64_encode($contents1)); 

//insert information into the database
mysql_query("INSERT INTO images (img,data)"."VALUES ('NULL', '$encoded')");

//delete the temporary file we made


Now thats the upload script complete, how do we view the images?

Second Page, "image.php":

//connect to database. Username and password need to be changed
$connection=mysql_connect("localhost", "username", "password");

//Select database, database_name needs to be changed

//get decoded image data from database
$result=mysql_query("SELECT * FROM images WHERE img='".$_GET['img']."'");

//fetch data from database

//note: "$data['data']" is the row "data" in the table we made.
//The image ID would be "$data['img']" for example

//close connection

//decode and echo the image data
echo base64_decode($encoded);


Now, test it. To view the images you upload go to:

and so on...

My first tutorial, tell me what you think. Did you find it hard to understand any parts?
Last edited:
0 0
The views expressed on this page by users and staff are their own, not those of NamePros.