Training, Open Source computer languages

PerlPHPPythonMySQLhttpd / TomcatTclRubyJavaC and C++LinuxCSS

Search our site for:
Home Accessibility Courses Diary The Mouth Forum Resources Site Map About Us Contact
Example - PHP form, Image upload. Store in MySQL database. Retrieve.

USING PHP AND MYSQL TO PROVIDE AN IMAGE LIBRARY

I'm often asked if MySQL can be used to store images - in other words as an image library. Yes, it can; you'll store the data using a "blob" type (longblob if the image might exceed 64k) and you need to ensure that the four characters " ' \ and null are encoded to that they don't cause the SQL statements any problems. Once you're aware of that, it shouldn't be any great problem. [[[And note - these techniques equally apply to .pdf document files and other binary data such as Word files ....]]]

When you come to "fronting" the database with PHP, it gets slightly more complex - you need to use an unusual encoding type in your form, and be very careful to get your file permissions, addslashes, stripslashes and htmlspecialschars all correct. If you're providing for public image upload, you also need to protect your script and server against the upload of copyright images, pornography, adverts for services that you don't want to advertise and other things against you acceptable user policy.

Here's a sample script that provide for image upload (maximum image size 145k, .jpg images only please) as a demonstration. It will only show you the most recent image even though lots are stored on the database.

This script may be run at /demo/pic_up.php4
The code is commented so that anyone with PHP skills can adopt and adapt to their needs. If you want some tips, please see the end of this article. A link back to our site if you do this would be appreciated ;-)

Link to us logo is at /resources/linktous.html
<?php

// Connect to database

$errmsg = "";
if (! @mysql_connect("localhost","trainee","abc123")) {
        $errmsg = "Cannot connect to database";
        }
@mysql_select_db("test");

// First run ONLY - need to create table by uncommenting this
// Or with silent @ we can let it fail every sunsequent time ;-)

$q = <<<CREATE
create table pix (
    pid int primary key not null auto_increment,
    title text,
    imgdata longblob)
CREATE;
@mysql_query($q);

// Insert any new image into database

if ($_REQUEST[completed] == 1) {
        // Need to add - check for large upload. Otherwise the code
        // will just duplicate old file ;-)
        // ALSO - note that latest.img must be public write and in a
        // live appliaction should be in another (safe!) directory.
        move_uploaded_file($_FILES['imagefile']['tmp_name'],"latest.img");
        $instr = fopen("latest.img","rb");
        $image = addslashes(fread($instr,filesize("latest.img")));
        if (strlen($instr) < 149000) {
                mysql_query ("insert into pix (title, imgdata) values (\"".
                $_REQUEST[whatsit].
                "\", \"".
                $image.
                "\")");
        } else {
                $errmsg = "Too large!";
        }
}

// Find out about latest image

$gotten = @mysql_query("select * from pix order by pid desc limit 1");
if ($row = @mysql_fetch_assoc($gotten)) {
        $title = htmlspecialchars($row[title]);
        $bytes = $row[imgdata];
} else {
        $errmsg = "There is no image in the database yet";
        $title = "no database image available";
        // Put up a picture of our training centre
        $instr = fopen("../wellimg/ctco.jpg","rb");
        $bytes = fread($instr,filesize("../wellimg/ctco.jpg"));
}

// If this is the image request, send out the image

if ($_REQUEST[gim] == 1) {
        header("Content-type: image/jpeg");
        print $bytes;
        exit ();
        }
?>

<html><head>
<title>Upload an image to a database</title>
<body bgcolor=white><h2>Here's the latest picture</h2>
<font color=red><?= $errmsg ?></font>
<center><img src=?gim=1 width=144><br>
<b><?= $title ?></center>
<hr>
<h2>Please upload a new picture and title</h2>
<form enctype=multipart/form-data method=post>
<input type=hidden name=MAX_FILE_SIZE value=150000>
<input type=hidden name=completed value=1>
Please choose an image to upload: <input type=file name=imagefile><br>
Please enter the title of that picture: <input name=whatsit><br>
then: <input type=submit></form><br>
<hr>
By Graham Ellis - graham@wellho.net
</body>
</html>

Note that this is a fully working example that you can try out on our server using the link above. For security reasons, we have changed the logins above but it works exactly as it's displayed above on our test systems. As you'll appreciate, various measures are taken with the online example (and those measures may change from time to time) to ensure the security and acceptability of content posting and this security may include changes that prevent posting and / or monitor your activity. See our privacy and copyright statement that's available as a link in the footer of this page.

TIPS IF YOU'RE INSTALLING THIS CODE YOURSELF

By its very nature, this script pulls together a whole raft of technologies which may or may not be installed / configure on your server ... if you have a shared hosting service, it may not work if facilities are missing or are not configured to a minimum level.

Firstly, you need to have installed on your server and available to you:

 a) MySQL - a recent 3.23 release, or MySQL 4 or MySQL 5
    (configured to allow you to create tables)
 b) PHP - version 4.1 or later with file upload enabled
    (if file upload is not enabled, it cannot work)
 c) the mysql_ set of mysql interfacing routines
    (this program version does NOT use the mysqli versions)

Secondly, you need to change the mysql_connect function call line to reflect the name of the database server you're using if it's a different machine, and the login account name and password that you use to access the database.

Thirdly, you need to change the mysql_select_db parameter to reflect the name of the database that you're using - one in which you have CREATE_PRIV.

If these facilities are not offered by your hosting service, then you won't be able to run my script or any other script that uses PHP and MySQL to upload images to a database. Please post on our Opentalk forum if you're not sure or want assistance - happy to help. Alas, I CANNOT help anonymous users of this page who tell me that the script doesn't work for them via the "rank and review" button ... their problem is probably one of the configuration issues listed above but I've no way of telling them :-/

A further example - handling .pdf files through PHP and a MySQL database can be found in my blog archive for December 2006.
Link to Opentalk Forum

See also PHP Course details

Please note that articles in this section of our web site were current and correct to the best of our ability when published, but by the nature of our business may go out of date quite quickly. The quoting of a price, contract term or any other information in this area of our website is NOT an offer to supply now on those terms - please check back via our main web site
Related Material

PHP - HTML Web Page Data Handling
Additional PHP Material
MySQL - Designing an SQL Database System
resource index - PHP
Solutions centre home page

You'll find shorter technical items at The Horse's Mouth and delegate's questions answered at the Opentalk forum.

At Well House Consultants, we provide training courses on subjects such as Ruby, Perl, Python, Linux, C, C++, Tcl/Tk, Tomcat, PHP and MySQL. We're asked (and answer) many questions, and answers to those which are of general interest are published in this area of our site.

Comment: "Thanks for this script. However, I have a problem. The ..."
Visitor Ranking 4.6 (5=excellent, 1=poor)

See also:
"4 characters in mysql" on the "Opentalk" forum
"Images in MySQL" on the "Opentalk" forum
"Using PHP and MySQL to provide an image library" on the "Opentalk" forum
"photo pin up" on the "Opentalk" forum
"Images from a database Multiple images per page" on the "Opentalk" forum
"Uploading images other binaries to MySQL via PHP" on the "Opentalk" forum
"outputing images from a php script help" on the "Opentalk" forum

Comment by Jelle (published 2008-04-26) Suggested link.
Thanks for this script. However, I have a problem. The images don't seem to upload at all.. my database sais 0kb and they don't display after uploading. I sometimes get an error about these two lines:
$instr = fopen("latest.img","rb");
$image = addslashes(fread($instr,filesize("latest.img")));

Everything else seems to work fine. I also have the mysql and php version required. A little help over here?

Grtz

PS I added the link to my website where I implemented the script. [#3359]

Comment by Ushno (published 2008-04-21)
Very useful script. I found it very much hepful. [#3358]

Comment by frustrated (published 2008-03-23)
worked to a point, it put the images in the db, but it did'nt display them as shown!
Mor significantly though, ho do i retrieve the images to a web page..?? left holing the baby [#3354]

Comment by Peter J (published 2008-01-01)
Thanx a lot! worked directly even for me as beginner in php, mysql. A suggestion is that you make it even more obviuos that the whole code should be in one page and not as in the first example.. [#3348]

Comment by Anon (published 2007-12-30)
Thanks a lot man. It works great. Just as soon as I can understand it all I will be off to the races. [#3346]

Comment by David Kadison (published 2007-12-19)
This worked perfectly for me - I changed, the database user, passwoord and name and it worked without a tweak...

Thank you so much [#3340]

Comment by Daniel Diaz (published 2007-10-16)
The code is really good. After a while i figured out the error. Just substitute "gim" for "pid". Trust me it will work. That was the whole bug. Lucky I found out. The funny thing is that I am not a programmer, I am just learning to do websites... Buena suerte amigos... [#3339]

Comment by Brijesh (published 2007-09-02)
WOW Script is very helpful [#3333]

Comment by Mark (published 2007-08-29)
Hi..
I got it run fine.

How can I call old image from the database?? [#3332]

Comment by Jem Smith (published 2007-07-14)
Hello
I'm Jem Smith devloper in infoseeksoftwaresystems.com
I'm unable to use this script.hwo can this make helpfule to me.
[#3326]

Comment by Graham (published 2007-07-10)
Dorit, thanks for your comments. This script is very much a demonstration of how the various PHP and MySQL and HTML form elements fit together. You (and anyone else) are welcome to add in your own validation in the form of passwording, [further] error checking, etc.

The matter of user validation for uploaded images is a very serious one indeed; at first glance, it could look as if we are leaving ourselves wide open on this site to image postings without any form of moderation. However, as users are only shown the latest images the system is self-correcting in that is someone posts an image that they should not, it will soon disappear as others get added on following.
[#3325]

Comment by Dorit (published 2007-07-10)
Quite interesting script, but I would want a password option and the filesize limit does not work - larger files plus title are still uploaded to the database (with no error message), but the pictures won't be able to show since they post with a size under the limit. However they don't seem to be resized, only somehow broken.
I testet the script test page here, and here also my picture title ended up being shown together with the next last uploaded picture, the latest picture which was under the size limit, excactly as I experience it with my own implementation, so it seems the problem is with the script, not my implementation of it. [#3324]

Comment by Graham (published 2007-05-10) Suggested link.
Albert, the source code of the other page may be handy there ... the coding to do it should be straightforward if you know some SQL (and if you don't, a question and answer session really isn't the best way to learn - click on the suggested link instead.

We have chosen NOT to display more than 3 on the other page for security reasons - allowing just 3 images to be seen on a fastmoving site means that it is selfmoderating - any nasty images soon get lost in the depths of time ;-) [#3317]

Comment by Albert (published 2007-05-10)
Great script, I only have one question.
Is it possible to view all the images in the database?
Can you also explain how you get up to three images on the other page where you can search through the db? [#3316]

Comment by Graham (published 2007-05-04)
Bastler, the limit is simply to stop people flooding our server although PHP does have an upload limit (much higher, configurable via the php.ini file) [#3315]

Comment by Bastler (published 2007-05-04)
just what I needed, thanks!
I have one question though:
The filesize limit you implement in the script, is this a "must have"-mySQL-Hardlimit or do you just want to prevent people from flooding your Database with DVD-ISOs?
In other words: if I use this script and limit access to it to trustworthy people, can I allow 5MB images or will it crash the database? [#3314]

Comment by Alan Hamlyn (published 2007-03-13) Suggested link.
I've seen this script for download elsewhere, i think its a possiblity it was taken... [#3309]

Comment by waqas (published 2007-03-10)
how to call images back for display.....!!!???
[#3308]

Comment by Larry (published 2006-12-16)
Really excellent example... thank you, Graham :o) [#3265]

Comment by Runar (published 2006-12-16)
Just wanted to say thanks for a very helpful script. [#3257]

Comment by Graham (published 2006-11-10) Suggested link.
Damu - I don't know which picture you saw. This page is open to anyone to test and, occasionally, unsuitable material gets posted. We do keep an eye on things, but because the page is so busy anything that's not suitable will only be seen for a few minutes before it's replaced by another image. [#3251]

Comment by taifa (published 2006-11-10)
GREAT [#3246]

Comment by damu (published 2006-11-10)
it's very super code but pls change the picture for ur example sit if it's having means cant able to open publicaly [#3242]

Comment by Graham (published 2006-09-27) Suggested link.
Dallas, the "gim=1" on the end of the URL is passing a parameter in as if it was a form that had been completed - the variable will get st in the $_GET and $_REQUEST superglobals.

Our "Rank and Review" system isn't best suited for technical questions such as this - we've an interactive forum at http://www.opentalk.org.uk where we can (and do) help people with questions on scripts such as this one. [#3239]

Comment by Dallas (published 2006-09-27)
Hi,

I just have one question... I'm not familiar with using your method of inserting the image data into the page:

if ($_REQUEST[gim] == 1) {
header("Content-type: image/jpeg");
print $bytes;
exit ();
}

and

img src=?gim=1 width=144

Do you have any references to using this method for inserting variables? Is there another way to insert the image without checking? Say if I want to print it in the page every time it loads?

Thanks,

D!
[#3232]

Comment by Anon (published 2006-09-07)
This was a great tutorial [#3230]

Comment by Graham Ellis (published 2006-08-26)
Yes, Josh - there is a (very slight) chance of there being a problem with latest.img on a very high use site. The script is written as it is to keep it straightforward for most people / applications. On a very high use site ... (a) use a function such as uniqid to generate a unique file name for the temporary file, (b) put the temporary file into a directory that's away from the document room at web server writeable and (c) use the unlink function to delete the temporary file after you've written it to the database. [#3229]

Comment by Josh (published 2006-08-26)
This is a great little script that I got successfully running with only a small amount of frustration. Only one question: Is there any chance that on a high traffic site, the latest.img file and database placement could display or store the wrong image? [#3228]

Comment by XSwebbX (published 2006-08-03)
Excellent, this is a brilliant example and has pointed me in the right direction! Great one. I'm just going to make some scripts so users can upload pics on my own project/website. [#3221]

Comment by Dejo (published 2006-07-13)
Svaka čast,odrađeno je super.And just one word on english PERFECT [#3211]

Comment by Graham (published 2006-06-14)
Wow - this page is busy! I've just looked at the "stats" and it's had 274 hits in the last 24 hours. The database of images that I reset every couple of week has 900 images in it .... looks like it works for most people, even if it's failing for poor old 'Anon' [#3204]

Comment by Graham (published 2006-06-14)
This script is dependant on you having PHP and MySQL available on your domain, and on you modifying the script to include your login details when you install in there. If it doesn't work for you, please read and check the list of pre-requisites and configurations carefully, and if that doesn't solve it for you please use our forum for help. [#3203]

Comment by Anon (published 2006-06-14)
Aw gee, another non-working image uploader. 0 bytes in the image field.

Gracias [#3201]

Comment by Kerry (published 2006-04-28) Suggested link.
Brilliant! been trying to figure out how to upload images for ages! Massive thanks!! [#393]

Comment by Anonymous (published 2006-03-25)
Finally, a concise, bare-bones and easy to understand instruction on how to get an image into and out of a blob. Thank you! [#373]

Comment by Jesus (published 2006-03-25)
Excellent example, for somebody that is learning PHP and Mysql like me...this script has saved me a lot of time. I've been for a week working in how to save pictures in a Mysql database, and this program works great. I already modify the size of the pictures and is working fine. [#371]

Comment by Anon (published 2006-03-25)
Quick question on your coding. Im trying to make it add another value into another field in the PIX table.. ive been trying to code for many hours and just cant understand where it gets the information fromthe form into the database.. if you could just explain quickly.. thank you [#351]

Comment by Adam Best (published 2006-03-25)
Great script - I've been looking for ages for one that works like this. Is it possible to edit the script so I can upload PDF's?

That would be the ultimate solution for me!

Thanks for your help [#347]

Comment by tim0fee (published 2006-03-25)
Hiya & thanks for sharing this knowledge!

Just found this tutorial - but I can't get the code to work on my local Apache/MySQL set up (even when I insert my correct login details for the database etc.)

All I am doing is copy/pasting the above code into a new file (foo.php) and dropping it into my server root folder. All I get is a blank page returned! :(

Any hints available please ? - I'd love to get it working

[#338]

Comment by Jo (published 2005-07-26)
I would just like to say a big thank you for this code. I have been trying to add images to mysql for the last few days and this is the first one I have found that works!
Thanks. [#332]

You can Add a comment or ranking or edit your own comments

Average page ranking - 4.6

© WELL HOUSE CONSULTANTS LTD., 2008: Well House Manor • 48 Spa Road • Melksham, Wiltshire • United Kingdom • SN12 7NY
PH: 01144 1225 708225 • FAX: 01144 1225 707126 • EMAIL: info@wellho.net • WEB: http://www.wellho.net • SKYPE: wellho