Home > PHP Scripts Examples and Tutorials > Uploading Files To MySQL Database
Maldives president resigns amid protests
UNP also protest at Hulftsdorp
Indian Coast Guard nabs 5 Lankan fishing boats
SL wins toss
SF brought to court
Get well soon, SLC tells Yuvi
We need democracy plus; Ranil
White flag appeal postponed
UNP DNA join hands in protest
India still ‘world class’ insists Mathews
SL to market Ayurveda drugs
Nine hand grenades found near Aluth Kade Court
Hirunika to join active politics
IPL teams splash the cash for Mahela and Murali
Anoma to lead protest to free SF
US diplomats heading to Sri Lanka
CID probing double murder in Kahawatta
Dr. R.H.S. Samaratunga appointed Sec to Petroleum Ministry
A/L fiasco - Probe team’s mandate limited
Three including police officer injured in Maligawatta shootout
Are you in Love?
10 Top Sex Secrets Men won't Tell
Top 10 — Female Turn Ons
10 Commandments for good wives
How to live a happy and satisfied Life
Did I marry the right person?
Are You Happy
Alcohol makes men BETTER in the bedroom, scientists claim
Too busy for Love Making?
Have you gone off sex?
Love Isn't Blind
Are You A Lazy Lover?
5 Secret Relationship Resolutions
Are You Getting Attracted To Another Person?
Do you feel loved?
Uploading Files To MySQL Database
Using PHP to upload files into MySQL database sometimes needed by some web application. For instance for storing pdf documents or images to make som kind of online briefcase (like Yahoo briefcase).
Uploading Files To MySQL Database
Using PHP to upload files into MySQL database sometimes needed by some web application. For instance for storing pdf documents or images to make som kind of online briefcase (like Yahoo briefcase).
For the first step, let's make the table for the upload files. The table will consist of.
- id : Unique id for each file
- name : File name
- type : File content type
- size : File size
- content : The file itself
For column content we'll use BLOB data type. BLOB is a binary large object that can hold a variable amount of data. MySQL have four BLOB data types, they are :
- TINYBLOB
- BLOB
- MEDIUMBLOB
- LONGBLOB
Since BLOB is limited to store up to 64 kilobytes of data we will use MEDIUMBLOB so we can store larger files ( up to 16 megabytes ).
Example : upload.txt
| CREATE TABLE upload ( id INT NOT NULL AUTO_INCREMENT, name VARCHAR(30) NOT NULL, type VARCHAR(30) NOT NULL, size INT NOT NULL, content MEDIUMBLOB NOT NULL, PRIMARY KEY(id) ); |
Uploading a file to MySQL is a two step process. First you need to upload the file to the server then read the file and insert it to MySQL.
For uploading a file we need a form for the user to enter the file name or browse their computer and select a file. The input type="file" is used for that purpose.
Example : upload.php
Source code : upload.phps
| <form method="post" enctype="multipart/form-data"> <table width="350" border="0" cellpadding="1" cellspacing="1" class="box"> <tr> <td width="246"> <input type="hidden" name="MAX_FILE_SIZE" value="2000000"> <input name="userfile" type="file" id="userfile"> </td> <td width="80"><input name="upload" type="submit" class="box" id="upload" value=" Upload "></td> </tr> </table> </form> |
An upload form must have encytype="multipart/form-data" otherwise it won't work at all. Of course the form method also need to be set to method="post". Also remember to put a hidden input MAX_FILE_SIZE before the file input. It's to restrict the size of files.
After the form is submitted the we need to read the autoglobal $_FILES. In the example above the input name for the file is userfile so the content of $_FILES are like this :
$_FILES['userfile']['name']
The original name of the file on the client machine.
$_FILES['userfile']['type']
The mime type of the file, if the browser provided this information. An example would be "image/gif".
$_FILES['userfile']['size']
The size, in bytes, of the uploaded file.
$_FILES['userfile']['tmp_name']
The temporary filename of the file in which the uploaded file was stored on the server.
$_FILES['userfile']['error']
The error code associated with this file upload. ['error'] was added in PHP 4.2.0
Example : upload.php
Source code : upload.phps
| <?php if(isset($_POST['upload']) && $_FILES['userfile']['size'] > 0) { $fileName = $_FILES['userfile']['name']; $tmpName = $_FILES['userfile']['tmp_name']; $fileSize = $_FILES['userfile']['size']; $fileType = $_FILES['userfile']['type']; $fp = fopen($tmpName, 'r'); $content = fread($fp, filesize($tmpName)); $content = addslashes($content); fclose($fp); if(!get_magic_quotes_gpc()) { $fileName = addslashes($fileName); } include 'library/config.php'; mysql_query($query) or die('Error, query failed'); |
PHP saves the uploaded file with a temporary name and save the name in $_FILES['userfile']['tmp_name']. Our next job is to read the content of this file and insert the content to database. Always make sure that you use addslashes() to escape the content. Using addslashes() to the file name is also recommended because you never know what the file name would be.
That's it now you can upload your files to MySQL. Now it's time to write the script to download those files.
Downloading Files From MySQL Database
When we upload a file to database we also save the file type and length. These were not needed for uploading the files but is needed for downloading the files from the database.
The download page list the file names stored in database. The names are printed as a url. The url would look like download.php?id=3. To see a working example click here. I saved several images in my database, you can try downloading them.
Example : download.php
Source code : download.phps
| <html> <head> <title>Download File From MySQL</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> </head> <body> $query = "SELECT id, name FROM upload"; |
When you click the download link, the $_GET['id'] will be set. We can use this id to identify which files to get from the database. Below is the code for downloading files from MySQL Database.
Example : download.php
Source code : download.phps
| <?php if(isset($_GET['id'])) { // if id is set then get the file with the id from database include 'library/config.php'; include 'library/opendb.php'; $id = $_GET['id']; header("Content-length: $size"); include 'library/closedb.php'; ?> |
Before sending the file content using echo first we need to set several headers. They are :
- header("Content-length: $size")
This header tells the browser how large the file is. Some browser need it to be able to download the file properly. Anyway it's a good manner telling how big the file is. That way anyone who download the file can predict how long the download will take.
- header("Content-type: $type")
This header tells the browser what kind of file it tries to download.
- header("Content-Disposition: attachment; filename=$name");
Tells the browser to save this downloaded file under the specified name. If you don't send this header the browser will try to save the file using the script's name (download.php).
After sending the file the script stops executing by calling exit.
NOTE :
When sending headers the most common error message you will see is something like this :
Warning: Cannot modify header information - headers already sent by (output started at C:Webrootlibraryconfig.php:7) in C:Webrootdownload.php on line 13
This error happens because some data was already sent before we send the header. As for the error message above it happens because i "accidentally" add one space right after the PHP closing tag ( ?> ) in config.php file. So if you see this error message when you're sending a header just make sure you don't have any data sent before calling header(). Check the file mentioned in the error message and go to the line number specified
Guidelines: You must register with a social media account such as Facebook, Twitter, Yahoo, etc. to comment on this story. Click on the "Login" button below to choose your login account of choice. We welcome your thoughts, but this is not an open forum. For the sake of all readers, please refrain from the use of obscenities, personal attacks or racial slurs. All comments must remain on topic and cyber bullying will not be tolerated. All comments are subject to our terms of service. Comments that do not comply may be removed. Repeat offenders will lose commenting privileges.
News Categories
Accidents and Incidents
Art and Society
Business and Finance
Education and Employment
Environment and Development
Help and Aid
Science and Technology
Security and Politics
Share Market and Exchange Rates
Sports and Entertainment
Tourism and Foreign Affairs
Women and Health
Information
Women and Health
Food Recipes
Love and Relationship
Web and IT
AJAX Examples and Tutorials
Java Scripts Examples and Tutorials
PHP Scripts Examples and Tutorials
Men want good-looking women
Making sex exciting
Duminda unmasked by Anarkali
Too busy for Love Making?
Srikanth Vandana got a Baby Boy-Father and Son Born on Same Day!
Anjali’s days with Bharathiraja and K. Balachandar
Have you gone off sex?
Sex and Shoes
Dirty Talk!
Happy Birthday Surya
Alcohol makes men BETTER in the bedroom, scientists claim
Sexless Marriages
Are You A Lazy Lover?
5 Secret Relationship Resolutions
Outsider Played Actress Sneha Hot Sexy Hip Cheap Photos?

































