Top Banner
3/21/12 E[aPSOe - PHP fRUP, IPage XSORad. SWRUe iQ M\SQL daWabaVe. ReWUieYe. 1/16 ZZZ.ZeOOhR.QeW/VROXWiRQV/ShS-e[aPSOe-ShS-fRUP-iPage-XSORad-VWRUe-iQ-P\VTO-daWabaVe-UeWUeiYe.hWPO Training, Open Source Computer Languages Perl PHP Python Tcl Ruby Lua C & C++ Java MySQL Tomcat Linux Search for: go Print friendly page Home Accessibilit\ Courses Diar\ The Mouth Forum Resources Site Map About Us Contact E[ample - PHP form, Image upload. Store in M\SQL 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 HTXDOO\ DSSO\ WR .SGI GRFXPHQW ILOHV DQG RWKHU ELQDU\ GDWD VXFK DV WRUG ILOHV ....]]] 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 subsequent time ;-) Public Training Courses Running regularly at our UK training Centre. [Schedule ] - [About ] - [Book ] PHP solutions Portrait of the Author of PHP Spotting and stopping denial of service attacks Using current exchange rates on a web page Using Frames with PHP Graphic User Interfaces (GUIs) An overview of PHP String functions Sourcing, installing and configuring PHP The practical solution of requirements using PHP Shopping cart application in PHP Complete PHP example - Registering for a get-together A Web interface for your Linux admin tasks Analysing incoming data lines Suggesting alternative search terms to web site users MySQL version 5, PHP version 5 and mysqli Nasty Characters in Web Applications What is PHP? Error messages in PHP Keeping the PHP and the HTML apart MySQL and PHP - enquiry tool for ad-hoc requirements
16

Example - PHP Form, Image Upload. Store in MySQL Database. Retrieve

Apr 21, 2015

Download

Documents

Keshav Kalra
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Example - PHP Form, Image Upload. Store in MySQL Database. Retrieve

3/21/12 Example - PHP form, Image upload. Store in MySQL database. Retrieve.

1/16www.wellho.net/solutions/php-example-php-form-image-upload-store-in-mysql-database-retreive.html

Training, Open Source Computer LanguagesPerl • PHP • Python • Tcl • Ruby • Lua • C & C++ • Java • MySQL • Tomcat • Linux

Search for: go

Print friendly page

Home Accessib ility 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 storethe data using a "blob" type (longblob if the image might exceed 64k) and you need to ensure that the fourcharacters " ' \ and null are encoded to that they don't cause the SQL statements any problems. Once you're awareof that, it shouldn't be any great problem. [[[And note - these techniques equally apply to .pdf document files andother 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 unusualencoding type in your form, and be very careful to get your file permissions, addslashes, stripslashes andhtmlspecialschars all correct. If you're providing for public image upload, you also need to protect your script andserver against the upload of copyright images, pornography, adverts for services that you don't want to advertise andother 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 ademonstration. 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 subsequent time ;-)

Public Training CoursesRunning regularly at our UK training Centre.[Schedule] - [About] - [Book]

PHP solutionsPortrait of the Author of PHP

Spotting and stopping denial of serviceattacks

Using current exchange rates on a webpage

Using Frames with PHP

Graphic User Interfaces (GUIs)

An overview of PHP String functions

Sourcing, installing and configuring PHP

The practical solution of requirements usingPHP

Shopping cart application in PHP

Complete PHP example - Registering for aget-together

A Web interface for your Linux admin tasks

Analysing incoming data lines

Suggesting alternative search terms to website users

MySQL version 5, PHP version 5 andmysqli

Nasty Characters in Web Applications

What is PHP?

Error messages in PHP

Keeping the PHP and the HTML apart

MySQL and PHP - enquiry tool for ad-hocrequirements

Page 2: Example - PHP Form, Image Upload. Store in MySQL Database. Retrieve

3/21/12 Example - PHP form, Image upload. Store in MySQL database. Retrieve.

2/16www.wellho.net/solutions/php-example-php-form-image-upload-store-in-mysql-database-retreive.html

$q = < < <CREATEcreate 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($image) < 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 ();

Example - PHP form, Image upload. Storein MySQL database. Retrieve.

Pattern Matching - a primer on regularExpressions

Interfacing applications to a MySQLdatabase engine

Web Page and HTML Spell Checker

What makes a good variab le name?

Solution Centre - all article listing

Page 3: Example - PHP Form, Image Upload. Store in MySQL Database. Retrieve

3/21/12 Example - PHP form, Image upload. Store in MySQL database. Retrieve.

3/16www.wellho.net/solutions/php-example-php-form-image-upload-store-in-mysql-database-retreive.html

}?>

<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 - [email protected]</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'llappreciate, various measures are taken with the online example (and those measures may change from time totime) to ensure the security and acceptability of content posting and this security may include changes that preventposting and / or monitor your activity. See our privacy and copyright statement that's available as a link in the footer ofthis 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 / configureon your server ... if you have a shared hosting service, it may not work if facilities are missing or are not configured toa 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'reusing if it's a different machine, and the login account name and password that you use to access the database.

Page 4: Example - PHP Form, Image Upload. Store in MySQL Database. Retrieve

3/21/12 Example - PHP form, Image upload. Store in MySQL database. Retrieve.

4/16www.wellho.net/solutions/php-example-php-form-image-upload-store-in-mysql-database-retreive.html

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 scriptthat uses PHP and MySQL to upload images to a database. Please post on our Opentalk forum if you're not sure orwant assistance - happy to help. Alas, I CANNOT help anonymous users of this page who tell me that the scriptdoesn't work for them via the "rank and review" button ... their problem is probably one of the configuration issueslisted 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 forDecember 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 youdebug / follow more closely while you're learning how to do this.

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 whenpublished, but by the nature of our business may go out of date quite quickly. The quoting of a price, contract term orany other information in this area of our website is NOT an offer to supply now on those terms - please check backvia 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)

Additional PHP Material [3210] Catchable fatal error in PHP ... How to catch, and alternative solutions such as JSON - (2011-03-22) [3118] Arrays of arrays - or 2D arrays. How to program tables. - (2011-01-02) [2684] Exception handling in PHP - (2010-03-18) [2215] If nothing, make it nothing. - (2009-06-02) [2073] Extra PHP Examples - (2009-03-09) [1623] PHP Techniques - a workshop - (2008-04-26) [1519] Flipping images on your web page - (2008-01-26) [1505] Script to present commonly used images - PHP - (2008-01-13)

Page 5: Example - PHP Form, Image Upload. Store in MySQL Database. Retrieve

3/21/12 Example - PHP form, Image upload. Store in MySQL database. Retrieve.

5/16www.wellho.net/solutions/php-example-php-form-image-upload-store-in-mysql-database-retreive.html

[1485] Copyright and theft of images, bandwidth and members. - (2007-12-26) [1451] More PHP sample and demonstration programs - (2007-12-01) [1391] Ordnance Survey Grid Reference to Latitude / Longitude - (2007-10-14) [1390] Converting from postal address to latitude / longitude - (2007-10-13) [1389] Controlling and labelling Google maps via PHP - (2007-10-13) [1270] PHP Standalone - keyboard to screen - (2007-07-18) [1194] Drawing hands on a clock face - PHP - (2007-05-19) [1104] Drawing dynamic graphs in PHP - (2007-03-09) [1053] Sorting people by name in PHP - (2007-01-26) [1020] Parallel processing in PHP - (2007-01-03) [1010] Dates, times, clickable diarys in PHP - (2006-12-28) [937] Display an image from a MySQL database in a web page via PHP - (2006-11-22) [917] Syntax checking in PHP - (2006-11-07) [839] Reporting on the 10 largest files or 10 top scores - (2006-08-20) [822] PHP - a team member leaves - (2006-08-04) [806] Check your user is human. Have him retype a word in a graphic - (2006-07-17) [789] Hot answers in PHP - (2006-07-02) [687] Presentation, Business and Persistence layers in Perl and PHP - (2006-04-17) [665] PHP Image viewing application - (2006-04-01) [603] PHP - setting sort order with an associative array - (2006-02-13) [563] Merging pictures using PHP and GD - (2006-01-13) [493] Running a Perl script within a PHP page - (2005-11-12) [483] Double Dollars in PHP - (2005-11-02) [468] Stand alone PHP programs - (2005-10-18) [372] Time calculation in PHP - (2005-07-08) [337] the array returned by preg_match_all - (2005-06-06) [322] More maps - (2005-05-23) [320] Ordnance Survey - using a 'Get a map' - (2005-05-22) [239] What and why for the epoch - (2005-03-08) [54] PHP and natural sorting - (2004-09-19)

MySQL - Designing an SQL Database System [3494] Databases - when to treat the rules as guidelines - (2011-10-23) [3361] Blowing our own trumpet - MySQL resources - (2011-07-18) [3270] SQL - Data v Metadata, and the various stages of data selection - (2011-04-29) [2749] Delegate Question - defining MySQL table relationships as you create the tables - (2010-05-02) [2204] Images in a database? How big is a database? (MySQL) - (2009-05-28) [2085] MySQL - licensing issues, even with using the name - (2009-03-16) [2053] What a difference a MySQL Index made - (2009-02-25) [1771] More HowTo diagrams - MySQL, Tomcat and Java - (2008-08-24) [1575] Database design for a shopping application (MySQL) - (2008-03-15) [1423] MySQL - table design and initial testing example - (2007-11-06) [945] Code quality counts - (2006-11-26) [937] Display an image from a MySQL database in a web page via PHP - (2006-11-22) [918] Databases needn't be frightening, hard or expensive - (2006-11-08) [666] Database design - get it right from first principles - (2006-04-02) [515] MySQL - an FAQ - (2005-12-03) [494] MySQL - a score of things to remember - (2005-11-12) [375] Oops - I got my initial database design wrong - (2005-07-12)

Page 6: Example - PHP Form, Image Upload. Store in MySQL Database. Retrieve

3/21/12 Example - PHP form, Image upload. Store in MySQL database. Retrieve.

6/16www.wellho.net/solutions/php-example-php-form-image-upload-store-in-mysql-database-retreive.html

[361] Binary Large Objects or bars - (2005-06-27) [59] MySQL - Pivot tables - (2004-09-22)

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, 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 ofgeneral interest are published in this area of our site.

Thank you for visiting us. This is our datamine where we give you some extra linksthat may be specially relevant to you ...based on what you entered in your searchstring and the part of the world you'rebased in.

* About Well House Consultants* Control statements in PHP* Functions in PHP* PHP objects* Analysing a programming task* PHP Courses* MySQL Courses* Books on PHP

Comment by xplicit (published 2011-09-18) Suggested link.Great Tutorial! Works the first time i run [#31012]

Comment by Daniel Liwonde (published 2011-05-24)It works fine this is really an excellent work! [#3932]

Comment by phptechie (published 2011-01-16) Suggested link.This is very usefull to me,its helps lot for my image uploading process..Thank you!! [#3850]

Comment by Jim Williams (published 2010-07-15)Questions about the construct "<img src=?gim=1 width=144>" are all over the Internet. When I view the pagesource 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]

Comment by Rob (published 2010-05-18)Terrific Graham, a script that actually works first time. Thanks. Are you available for support / consultancy? [#3561]

Comment by Swetha (published 2010-03-21)i got this code it is working properly [#3487]

Comment by Ramakrishnan (published 2009-12-28)Well,it is working good,Thanks for your great work...

Page 7: Example - PHP Form, Image Upload. Store in MySQL Database. Retrieve

3/21/12 Example - PHP form, Image upload. Store in MySQL database. Retrieve.

7/16www.wellho.net/solutions/php-example-php-form-image-upload-store-in-mysql-database-retreive.html

Thanks Ramakrishnan t [#3446]

Comment by Sanjay (published 2009-12-28)Hy. The code that has been used to upload and display pictures from the mysql database is very good. The pictureis saved in the database. Though i am having problems displaying the picture. I tried that gim=1 thing and i triedsubstituting the gim to pid. Nothiong seems to work. please if someone can assist me i would highly appreciate it. Sanjay [#3442]

Comment by redRoger (published 2010-01-18) Suggested link.I had made some changes to the script because when trying to import to a external Database for ExampleMyphpAdmin it will give some upload error. This is the new mod that works....

<?php

// Connect to database$errmsg = "";

$db = mysql_connect($hostname,$username, $password) or die ("<html><scriptlanguage='JavaScript'>alert('Unable to connect to database! Please try again later.'),history.go(-1)</script></html>");mysql_select_db($dbname);

// 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.$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!";}}

// Find out about latest image

$gotten = @mysql_query("select * from pix order by pid desc limit 1");if ($row = @mysql_fetch_assoc($gotten)) {

Page 8: Example - PHP Form, Image Upload. Store in MySQL Database. Retrieve

3/21/12 Example - PHP form, Image upload. Store in MySQL database. Retrieve.

8/16www.wellho.net/solutions/php-example-php-form-image-upload-store-in-mysql-database-retreive.html

$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("assets/ctco.jpg","rb");$bytes = fread($instr,filesize("assets/ctco.jpg"));}

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

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

Comment by Alex (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 imageinto SQL and every image suppose to belong to his data.This script works good.But i need insert image in thesame table where is data in and after retreive it with data.Please help.Thanks a lot [#3435]

Comment by Anon (published 2009-10-27)This is an excellent tutorial, just what i have been searching for! well done! [#3429]

Comment by (published 2009-10-27)Please do not use the picture which I uploaded. I saw the message below after I uploaded the image. [#3427]

Comment by Graham (published 2009-06-30) Suggested link.I've provided a link to our help forum on this review - that is a far better vehicle for support that this comment section.

There are many elements involved in an upload / store / retreive / download script and you need to know some PHPand MySQL to implement on your own server - things like account names need changing, and perhaps spurieousspaces from line wraps on your browser taking out. [#3424]

Comment by bimbolera (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 imagesuploaded will be viewed. i hope i can get a comment over this. [#3423]

Comment by Ashish (published 2009-06-16)Thanks a lot! it was superb... nothing else on the web worked. [#3415]

Comment by sukanta (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

Page 9: Example - PHP Form, Image Upload. Store in MySQL Database. Retrieve

3/21/12 Example - PHP form, Image upload. Store in MySQL database. Retrieve.

9/16www.wellho.net/solutions/php-example-php-form-image-upload-store-in-mysql-database-retreive.html

then data and image is inserted but when i am selecting the pix table to show image and title it selecting title butnot getting image..plz give a solution..thankssukanta [#3395]

Comment by Greg (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");

// Create table if not already present

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

mysqli_query($link,$q);

// Insert any new image into database

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!";}}

// Find out about latest image

$gotten = mysqli_query($link,"select * from pix order by pid desc limit 1");

Page 10: Example - PHP Form, Image Upload. Store in MySQL Database. Retrieve

3/21/12 Example - PHP form, Image upload. Store in MySQL database. Retrieve.

10/16www.wellho.net/solutions/php-example-php-form-image-upload-store-in-mysql-database-retreive.html

if ($row = mysqli_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";}

// 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 - [email protected] modified for mysqli by Greg Gordon - [email protected]</body></html> [#3384]

Comment by Anon (published 2008-11-09)yes -- one that actually works , and is well commentedthx ...Graham [#3371]

Comment by xaian (published 2008-07-16)thanks ur the man... [#3370]

Comment by Anon (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 codeto display the images.**************************************************mysql_connect($db_host, $db_user, $db_pwd);mysql_select_db($db_name);

Page 11: Example - PHP Form, Image Upload. Store in MySQL Database. Retrieve

3/21/12 Example - PHP form, Image upload. Store in MySQL database. Retrieve.

11/16www.wellho.net/solutions/php-example-php-form-image-upload-store-in-mysql-database-retreive.html

$SQLgetImages = "SELECT * FROM pix ORDER BY pid";$getImagesNow = mysql_query ($SQLgetImages);if (mysql_num_rows ($getImagesNow) == 0){echo "There are no images.";}else{while ($row = mysql_fetch_array ($getImagesNow)) {echo "<br>Title:" . $row["title"] . "Image:<img src=upload/". isset($row['imagefile']) . "><br>";}} [#3361]

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 0kband 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 moreobviuos 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. Thatwas the whole bug. Lucky I found out. The funny thing is that I am not a programmer, I am just learning to do

Page 12: Example - PHP Form, Image Upload. Store in MySQL Database. Retrieve

3/21/12 Example - PHP form, Image upload. Store in MySQL database. Retrieve.

12/16www.wellho.net/solutions/php-example-php-form-image-upload-store-in-mysql-database-retreive.html

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.comI'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 andHTML form elements fit together. You (and anyone else) are welcome to add in your own validation in the form ofpasswording, [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 weare leaving ourselves wide open on this site to image postings without any form of moderation. However, as usersare only shown the latest images the system is self-correcting in that is someone posts an image that they shouldnot, 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 plustitle are still uploaded to the database (with no error message), but the pictures won't be able to show since theypost 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 lastuploaded picture, the latest picture which was under the size limit, excactly as I experience it with my ownimplementation, 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 youknow some SQL (and if you don't, a question and answer session really isn't the best way to learn - click on thesuggested link instead.

We have chosen NOT to display more than 3 on the other page for security reasons - allowing just 3 images to beseen 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?

Page 13: Example - PHP Form, Image Upload. Store in MySQL Database. Retrieve

3/21/12 Example - PHP form, Image upload. Store in MySQL database. Retrieve.

13/16www.wellho.net/solutions/php-example-php-form-image-upload-store-in-mysql-database-retreive.html

[#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 preventpeople 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 crashthe 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, unsuitablematerial gets posted. We do keep an eye on things, but because the page is so busy anything that's not suitablewill 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 athttp://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,

Page 14: Example - PHP Form, Image Upload. Store in MySQL Database. Retrieve

3/21/12 Example - PHP form, Image upload. Store in MySQL database. Retrieve.

14/16www.wellho.net/solutions/php-example-php-form-image-upload-store-in-mysql-database-retreive.html

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 imagewithout 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 scriptis written as it is to keep it straightforward for most people / applications. On a very high use site ... (a) use afunction such as uniqid to generate a unique file name for the temporary file, (b) put the temporary file into adirectory that's away from the document room at web server writeable and (c) use the unlink function to delete thetemporary 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 thewrong 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 makesome scripts so users can upload pics on my own project/website. [#3221]

Comment by Dejo (published 2006-07-13)Svaka &#269;ast,odra&#273;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 ofimages that I reset every couple of week has 900 images in it .... looks like it works for most people, even if it'sfailing 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

Page 15: Example - PHP Form, Image Upload. Store in MySQL Database. Retrieve

3/21/12 Example - PHP form, Image upload. Store in MySQL database. Retrieve.

15/16www.wellho.net/solutions/php-example-php-form-image-upload-store-in-mysql-database-retreive.html

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'vebeen for a week working in how to save pictures in a Mysql database, and this program works great. I alreadymodify 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 beentrying to code for many hours and just cant understand where it gets the information fromthe form into thedatabase.. 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 uploadPDF'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 mycorrect 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 Iget 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 daysand this is the first one I have found that works!

Page 16: Example - PHP Form, Image Upload. Store in MySQL Database. Retrieve

3/21/12 Example - PHP form, Image upload. Store in MySQL database. Retrieve.

16/16www.wellho.net/solutions/php-example-php-form-image-upload-store-in-mysql-database-retreive.html

Thanks. [#332]

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

Average page ranking - 4.7

© WELL HOUSE CONSULTANTS LTD., 2012: Well House Manor • 48 Spa Road • Melksham, Wiltshire • United Kingdom • SN12 7NYPH: +44 (0)1225 708225 • FAX: +44 (0)1225 899360 • EMAIL: [email protected] • 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: wizard