Search for: go
Print friendly page
Home Accessib ilit Courses Diar The Mouth Forum Resources Site Map Ab out Us Contact
E ample - PHP form, Image upload. Store in M SQL database. Retrieve. Public Training Courses
Running regularly at our UK training Centre.
[Schedule] - [Ab out] - [Book]
USING PHP AND MYSQL TO PROVIDE AN IMAGE LIBRARY
PHP solutions
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 Portrait of the Author of PHP
the data using a "blob" type (longblob if the image might exceed 64k) and you need to ensure that the four Spotting and stopping denial of service
characters " ' \ and null are encoded to that they don't cause the SQL statements any problems. Once you're aware attacks
of that, it shouldn't be any great problem. [[[And note - these techniques .
W ....]]] Using current exchange rates on a web
page
When you come to "fronting" the database with PHP, it gets slightly more complex - you need to use an unusual Using Frames with PHP
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 Graphic User Interfaces (GUIs)
server against the upload of copyright images, pornography, adverts for services that you don't want to advertise and An overview of PHP String functions
other things against you acceptable user policy.
Sourcing, installing and configuring PHP
Here's a sample script that provide for image upload (maximum image size 145k, .jpg images only please) as a The practical solution of requirements using
demonstration. It will only show you the most recent image even though lots are stored on the database. PHP
Shopping cart application in PHP
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, Complete PHP example - Registering for a
please see the end of this article. A link back to our site if you do this would be appreciated ;-) get-together
A Web interface for your Linux admin tasks
Link to us logo is at /resources/linktous.html
Analysing incoming data lines
<?php Suggesting alternative search terms to web
site users
// Connect to database
MySQL version 5, PHP version 5 and
$errmsg = ""; mysqli
if (! @mysql_connect("localhost","trainee","abc123")) { Nasty Characters in Web Applications
$errmsg = "Cannot connect to database";
What is PHP?
@mysql_select_db("test"); Error messages in PHP
Keeping the PHP and the HTML apart
// First run ONLY - need to create table by uncommenting this
// Or with silent @ we can let it fail every subsequent time ;-) MySQL and PHP - enquiry tool for ad-hoc
requirements
if ($_REQUEST[gim] == 1) {
header("Content-type: image/jpeg");
print $bytes;
exit ();
. e h . e/ i / h -e a e- h -f -i age- ad- e-i - -da aba e- e ei e.h 2/16
3/21/12 E a e - PHP f , I age ad. S e i M SQL da aba e. Re ie e.
?>
<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.
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:
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.
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 datab ase can be found in my b log archive for
Decemb er 2006.
Link to our Ask the tutor forum
August 2010 - I have added a further example set [here] in which I have split the process into three steps to help you
debug / follow more closely while you're learning how to do this.
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
[3036] Sending out an email containing HTML from within a PHP page - (2010-11-07)
[2135] What features does this visitors browser support? (PHP) - (2009-04-22)
[2107] How to tweet automatically from a blog - (2009-03-28)
[2046] Finding variations on a surname - (2009-02-17)
[2025] Injection Attack if register_globals in on - PHP - (2009-02-04)
[1831] Text formating for HTML, with PHP - (2008-10-11)
[1169] Emailing as HTML (Web Page) - PHP example - (2007-04-30)
[1136] Buffering output - why it is done and issues raised in Tcl, Perl, Python and PHP - (2007-04-06)
[1053] Sorting people by name in PHP - (2007-01-26)
[1001] .pdf files - upload via PHP, store in MySQL, retrieve - (2006-12-19)
[896] PHP - good coding practise and sticky radio buttons - (2006-10-17)
[789] Hot answers in PHP - (2006-07-02)
[589] Robust PHP user inputs - (2006-02-03)
[50] Current cost in your local currency - (2004-09-16)
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, Lua, 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.
Thank you for visiting us. This is our data * Ab out Well House Consultants
mine where we give you some extra links * Control statements in PHP
that may be specially relevant to you ... * Functions in PHP
based on what you entered in your search * PHP ob jects
string and the part of the world you're * Analysing a programming task
based in. * PHP Courses
* MySQL Courses
* Books on PHP
C D L (published 2011-05-24)
It works fine this is really an excellent work! [#3932]
C J W (published 2010-07-15)
Questions about the construct "<img src=?gim=1 width=144>" are all over the Internet. When I view the page
source for http://www.wellho.net/demo/pic_up.php4, Firefox treats "?gim=1" as if it were a hyperlink. I gather that "?
gim=1" is some sort of data URL, but every example of data URLs I can find uses the base64 encoding. [#3631]
C R (published 2010-05-18)
Terrific Graham, a script that actually works first time. Thanks. Are you available for support / consultancy? [#3561]
C S (published 2010-03-21)
i got this code it is working properly [#3487]
C R (published 2009-12-28)
Well,it is working good,Thanks for your great work...
C S (published 2009-12-28)
Hy. The code that has been used to upload and display pictures from the mysql database is very good. The picture
is saved in the database. Though i am having problems displaying the picture. I tried that gim=1 thing and i tried
substituting the gim to pid. Nothiong seems to work. please if someone can assist me i would highly appreciate it.
Sanjay [#3442]
<?php
// Connect to database
$errmsg = "";
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.
$uploaded_dir = 'temporary';
$path = $uploaded_dir . $filename;
$filename = $_FILES['imagefile']['tmp_name'];
$instr = fopen($filename,'rb');
$image = addslashes(fread($instr,filesize($filename)));
if (strlen($instr) < 200000) {
mysql_query ("insert into pix (title, imgdata) values (\"".
$_REQUEST[whatsit].
"\", \"".
$image.
"\")");
} else {
$errmsg = "Too large!";
}
}
if ($_REQUEST[gim] == 1) {
header("Content-type: image/jpeg");
print $bytes;
exit ();
}
?> [#3440]
C A (published 2009-10-27)
Nice work.Thank you.On web site user post item with image through post form.I need insert the data and image
into SQL and every image suppose to belong to his data.This script works good.But i need insert image in the
same table where is data in and after retreive it with data.Please help.Thanks a lot [#3435]
C A (published 2009-10-27)
This is an excellent tutorial, just what i have been searching for! well done! [#3429]
C (published 2009-10-27)
Please do not use the picture which I uploaded. I saw the message below after I uploaded the image. [#3427]
There are many elements involved in an upload / store / retreive / download script and you need to know some PHP
and MySQL to implement on your own server - things like account names need changing, and perhaps spurieous
spaces from line wraps on your browser taking out. [#3424]
C (published 2009-06-30)
to everyone who encountered the IMAGE DOES NOT SHOW the key to this is fine the <center><img src=
width=144><br> part of the html, you will see there that the img src part is blank so paste this ?gim=1 after the src=
and your problem is solved. now my new problem is i've made another page wherein i wish that all the images
uploaded will be viewed. i hope i can get a comment over this. [#3423]
C A (published 2009-06-16)
Thanks a lot! it was superb... nothing else on the web worked. [#3415]
C (published 2009-06-02)
hey!!thanks for your script..
i am using it in my site.when i am using it within a page its working nice but when i am using it with another form
. e h . e/ i / h -e a e- h -f -i age- ad- e-i - -da aba e- e ei e.h 8/16
3/21/12 E a e - PHP f , I age ad. S e i M SQL da aba e. Re ie e.
then data and image is inserted but when i am selecting the pix table to show image and title it selecting title but
not getting image..plz give a solution..
thanks
sukanta [#3395]
C G (published 2008-12-31)
Here is the mysqli modification:
<?php
// Connect to database
$link = mysqli_connect("localhost","user","password");
$errmsg = "";
if (! $link) {
$errmsg = "Cannot connect to database";
}
mysqli_select_db($link,"test");
mysqli_query($link,$q);
if ($_REQUEST[completed] == 1) {
move_uploaded_file("imagefile","latest.img");
$instr = fopen("latest.img","rb");
$image = addslashes(fread($instr,filesize("latest.img")));
if (strlen($instr) < 149000) {
mysqli_query ($link,"insert into pix (title, imgdata) values (\"".
$_REQUEST[whatsit].
"\", \"".
$image.
"\")");
} else {
$errmsg = "Too large!";
}
}
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 modified for mysqli by Greg Gordon - cydoc@earthlink.net
</body>
</html> [#3384]
C A (published 2008-11-09)
yes -- one that actually works , and is well commented
thx ...Graham [#3371]
C (published 2008-07-16)
thanks ur the man... [#3370]
C A (published 2008-06-05)
HELP! I have the scrip working fine, except I'm having a hard time displaying the image. I'm using the following code
to display the images.
**************************************************
mysql_connect($db_host, $db_user, $db_pwd);
mysql_select_db($db_name);
. e h . e/ i / h -e a e- h -f -i age- ad- e-i - -da aba e- e ei e.h 10/16
3/21/12 E a e - PHP f , I age ad. S e i M SQL da aba e. Re ie e.
Everything else seems to work fine. I also have the mysql and php version required. A little help over here?
Grtz
C U (published 2008-04-21)
Very useful script. I found it very much hepful. [#3358]
C (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]
C P 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]
C A (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]
C D K (published 2007-12-19)
This worked perfectly for me - I changed, the database user, passwoord and name and it worked without a tweak...
C D D (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
. e h . e/ i / h -e a e- h -f -i age- ad- e-i - -da aba e- e ei e.h 11/16
3/21/12 E a e - PHP f , I age ad. S e i M SQL da aba e. Re ie e.
websites... Buena suerte amigos... [#3339]
C B (published 2007-09-02)
WOW Script is very helpful [#3333]
C M (published 2007-08-29)
Hi..
I got it run fine.
C J S (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]
C G (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]
C D (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]
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]
C A (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?
. e h . e/ i / h -e a e- h -f -i age- ad- e-i - -da aba e- e ei e.h 12/16
3/21/12 E a e - PHP f , I age ad. S e i M SQL da aba e. Re ie e.
[#3316]
C G (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]
C B (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]
C (published 2007-03-10)
how to call images back for display.....!!!???
[#3308]
C L (published 2006-12-16)
Really excellent example... thank you, Graham :o) [#3265]
C R (published 2006-12-16)
Just wanted to say thanks for a very helpful script. [#3257]
C (published 2006-11-10)
GREAT [#3246]
C (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]
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]
C D (published 2006-09-27)
Hi,
if ($_REQUEST[gim] == 1) {
header("Content-type: image/jpeg");
print $bytes;
exit ();
}
and
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]
C A (published 2006-09-07)
This was a great tutorial [#3230]
C G E (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]
C J (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]
C XS X (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]
C D (published 2006-07-13)
Svaka čast,odrađeno je super.And just one word on english PERFECT [#3211]
C G (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]
C G (published 2006-06-14)
This script is dependant on you having PHP and MySQL available on your domain, and on you modifying the script
. e h . e/ i / h -e a e- h -f -i age- ad- e-i - -da aba e- e ei e.h 14/16
3/21/12 E a e - PHP f , I age ad. S e i M SQL da aba e. Re ie e.
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]
C A (published 2006-06-14)
Aw gee, another non-working image uploader. 0 bytes in the image field.
Gracias [#3201]
C A (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]
C J (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]
C A (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]
C A B (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?
C 0 (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! :(
[#338]
C J (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!
. e h . e/ i / h -e a e- h -f -i age- ad- e-i - -da aba e- e ei e.h 15/16
3/21/12 E a e - PHP f , I age ad. S e i M SQL da aba e. Re ie e.
Thanks. [#332]
WELL HOUSE CONSULTANTS LTD., 2012: Well House Manor 48 Spa Road Melksham, Wiltshire United Kingdom SN12 7NY
PH: +44 (0)1225 708225 FAX: +44 (0)1225 899360 EMAIL: info@wellho.net WEB: http://www.wellho.net SKYPE: wellho
PAGE: http://www.wellho.net/solutions/php-exam ... reive.html PAGE BUILT: Sat Aug 14 06:07:39 2010 BUILD SYSTEM: wi ard