SlideShare a Scribd company logo
1 of 8
Uploading files into a MySQL database using PHP

Atli
You may be wondering why you would want to put your files “into” the database, rather than
just onto the file-system. Well, most of the time, you wouldn’t.

In situations where your PHP application needs to store entire files, the preferred method is
to save the file onto the server’s file-system, and store the physical location of the file in your
database. This is generally considered to be the easiest and fastest way to store files.

However, you may find yourself in situations where you would want to keep the file itself with
the other data in your database. This gives you - or rather: MySQL - complete control over
the file data, rather than just the location of the file on the server.

There are some downsides to this method though, such as; decreased performance and
added complexity to both your PHP code and your database structure. This is something you
should carefully consider before using this in a real-life application.

Having said that, this article demonstrates how you can upload a file from a browser into
MySQL, and how to send the files back to the browser.

Before you start
To get through this smoothly, you should be familiar with the following:

    •   PHP Basics
    •   MySQL Basics
    •   Using MySQL in PHP (mysqli)
    •   HTML Forms and how to handle POST data in PHP.



The battle plan
As with all programs, before we start writing we need to plan a little ahead. Just so we know
what we are going to write before we write it.

Before we start on the program, we need to design the database. This is not a complex
design, as we are not talking about creating some complex filing system. We only need a
single table, containing a BLOB field for our file and various other fields to store information
on our file, such as name, size, type.

Now then. The first phase of the program is getting the file from our users onto the server
where our PHP can interact with it. This is the simplest part of the process, requiring only a
basic HTML form.
The second phase involves reading the uploaded file, making sure it was uploaded
successfully and adding it to the database. This is a similar process as the one used when
uploading a file to the file-system, but using the MySQL functions rather than the file-system
functions.

The third phase is to list all files that have been uploaded and saved on the database, with a
link so it can be downloaded. The only problem here would be the fact that the file does not
exists on the server, so how do we create a link to it? That is a problem handled by phase 4,
all we need to do in phase 3 is create a link with the ID of the file to be downloaded
embedded in the URL.

The fourth, and final, part is the one that is most confusing about this process. The part
where we fetch the file and send it to the client's browser.
We start by using the MySQL functions, and the ID sent by phase 3, to fetch the file data
from the database. Then we set a few headers, letting the browser know what to expect,
before finally sending the contents of the file.

Now, using this summary as a guide, lets start writing our program.

Phase 0: Building a database
The database is simple. One table with a BLOB field for the file data and a few fields for
various pieces of information relating to the file:
Expand|Select|Wrap|Line Numbers

         1. CREATE TABLE `file` (
         2.     `id`        Int Unsigned Not Null Auto_Increment,
         3.     `name`      VarChar(255) Not Null Default 'Untitled.txt',
         4.     `mime`      VarChar(50) Not Null Default 'text/plain',
         5.     `size`      BigInt Unsigned Not Null Default 0,
         6.     `data`      MediumBlob Not Null,
         7.     `created`   DateTime Not Null,
         8.     PRIMARY KEY (`id`)
         9. )
         10.


As you see, we store the file name, including the extension.
We have the mime type, which we use to let the browser know what kind of file we are
dealing with.
The size of the file in bytes.
And finally the data itself, in a MediumBlob field.

Phase 1: Uploading the file
Now, we need to get the file from the user. The table we designed does not require any
additional information from the user, so we will make this simple and create a HTML form
with only a single "file" input field and a submit button:
Expand|Select|Wrap|Line Numbers

         1. <!DOCTYPE html>
         2. <head>
         3.      <title>MySQL file upload example</title>
         4.      <meta http-equiv="content-type" content="text/html; charset=U
             TF-8">
         5. </head>
         6. <body>
         7.      <form action="add_file.php" method="post" enctype="multipart/
             form-data">
         8.           <input type="file" name="uploaded_file"><br>
         9.           <input type="submit" value="Upload file">
         10.     </form>
         11.     <p>
         12.          <a href="list_files.php">See all files</a>
         13.     </p>
         14.</body>
         15.</html>


Note the third attribute of the <form> element, "enctype". This tells the browser how to send
the form data to the server. As it is, when sending files, this must be set to "multipart/form-
data".
If it is set any other way, or not set at all, your file is probably not going to be transmitted
correctly.

At the bottom, we have a link to the list we will create in phase 3.

Phase 2: Add the file to the database
In the form we built in phase 1, we set the action property to "add_file.php". This is the file we
are going to build it this phase of the process.

This file needs to check if a file has been uploaded, make sure it was uploaded without
errors, and add it to the database:
Expand|Select|Wrap|Line Numbers

         1. <?php
         2. // Check if a file has been uploaded
         3. if(isset($_FILES['uploaded_file'])) {
         4.     // Make sure the file was sent without errors
         5.     if($_FILES['uploaded_file']['error'] == 0) {
         6.         // Connect to the database
         7.         $dbLink = new mysqli('127.0.0.1', 'user', 'pwd', 'myTable');
8.         if(mysqli_connect_errno()) {
9.             die("MySQL connection failed: ". mysqli_connect_error());
10.        }
11.
12.         // Gather all required data
13.         $name = $dbLink->real_escape_string($_FILES['uploaded_file']
    ['name']);
14.         $mime = $dbLink->real_escape_string($_FILES['uploaded_file']
    ['type']);
15.         $data = $dbLink->real_escape_string(file_get_contents($_FILES
     ['uploaded_file']['tmp_name']));
16.         $size = intval($_FILES['uploaded_file']['size']);
17.
18.         // Create the SQL query
19.         $query = "
20.            INSERT INTO `file` (
21.                `name`, `mime`, `size`, `data`, `created`
22.            )
23.            VALUES (
24.                '{$name}', '{$mime}', {$size}, '{$data}', NOW()
25.            )";
26.
27.        // Execute the query
28.        $result = $dbLink->query($query);
29.
30.        // Check if it was successfull
31.        if($result) {
32.            echo 'Success! Your file was successfully added!';
33.        }
34.        else {
35.            echo 'Error! Failed to insert the file'
36.               . "<pre>{$dbLink->error}</pre>";
37.        }
38.     }
39.     else {
40.         echo 'An error accured while the file was being uploaded. '
41.            . 'Error code: '. intval($_FILES['uploaded_file']
    ['error']);
42.     }
43.
44.     // Close the mysql connection
45.     $dbLink->close();
46. }
47. else {
48.     echo 'Error! A file was not sent!';
49. }
50.
51. // Echo a link back to the main page
         52. echo '<p>Click <a href="index.html">here</a> to go back</p>';
         53. ?>
         54.


Phase 3: Listing all existing files
So, now that we have a couple of files in our database, we need to create a list of files and
link them so they can be downloaded:
Expand|Select|Wrap|Line Numbers

         1.   <?php
         2.   // Connect to the database
         3.   $dbLink = new mysqli('127.0.0.1', 'user', 'pwd', 'myTable');
         4.   if(mysqli_connect_errno()) {
         5.       die("MySQL connection failed: ". mysqli_connect_error());
         6.   }
         7.
         8.  // Query for a list of all existing files
         9.  $sql = 'SELECT `id`, `name`, `mime`, `size`, `created` FROM `file
             `';
         10.$result = $dbLink->query($sql);
         11.
         12.// Check if it was successfull
         13.if($result) {
         14.     // Make sure there are some files in there
         15.     if($result->num_rows == 0) {
         16.         echo '<p>There are no files in the database</p>';
         17.     }
         18.     else {
         19.         // Print the top of a table
         20.         echo '<table width="100%">
         21.                 <tr>
         22.                      <td><b>Name</b></td>
         23.                      <td><b>Mime</b></td>
         24.                      <td><b>Size (bytes)</b></td>
         25.                      <td><b>Created</b></td>
         26.                      <td><b>&nbsp;</b></td>
         27.                 </tr>';
         28.
         29.         // Print each file
         30.         while($row = $result->fetch_assoc()) {
         31.             echo "
         32.                 <tr>
         33.                      <td>{$row['name']}</td>
         34.                      <td>{$row['mime']}</td>
         35.                      <td>{$row['size']}</td>
         36.                      <td>{$row['created']}</td>
37.                      <td><a href='get_file.php?
             id={$row['id']}'>Download</a></td>
         38.                 </tr>";
         39.         }
         40.
         41.         // Close table
         42.         echo '</table>';
         43.     }
         44.
         45.     // Free the result
         46.     $result->free();
         47.}
         48.else
         49.{
         50.     echo 'Error! SQL query failed:';
         51.     echo "<pre>{$dbLink->error}</pre>";
         52.}
         53.
         54.// Close the mysql connection
         55.$dbLink->close();
         56.?>


Phase 4: Downloading a file
This part is the one that usually causes the most confusion.

To really understand how this works, you must understand how your browser downloads
files. When a browser requests a file from a HTTP server, the server response will include
information on what exactly it contains. These bits of information are called headers. The
headers usually include information on the type of data being sent, the size of the response,
and in the case of files, the name of the file.

There are of course a lot of other headers, which I will not cover here, but it is worth looking
into!

Now, this code. We start simply by reading the ID sent by the link in phase 3. If the ID is
valid, we fetch the information on the file who's ID we received, send the headers, and finally
send the file data:
Expand|Select|Wrap|Line Numbers

         1.    <?php
         2.    // Make sure an ID was passed
         3.    if(isset($_GET['id'])) {
         4.    // Get the ID
         5.        $id = intval($_GET['id']);
         6.
7.           // Make sure the ID is in fact a valid ID
8.           if($id <= 0) {
9.               die('The ID is invalid!');
10.          }
11.          else {
12.              // Connect to the database
13.              $dbLink = new mysqli('127.0.0.1', 'user', 'pwd', 'myTable
      ');
14.              if(mysqli_connect_errno()) {
15.                  die("MySQL connection failed: ". mysqli_connect_error
      ());
16.              }
17.
18.              // Fetch the file information
19.              $query = "
20.                  SELECT `mime`, `name`, `size`, `data`
21.                  FROM `file`
22.                  WHERE `id` = {$id}";
23.              $result = $dbLink->query($query);
24.
25.              if($result) {
26.                  // Make sure the result is valid
27.                  if($result->num_rows == 1) {
28.                  // Get the row
29.                      $row = mysqli_fetch_assoc($result);
30.
31.                   // Print headers
32.                   header("Content-Type: ". $row['mime']);
33.                   header("Content-Length: ". $row['size']);
34.                   header("Content-Disposition: attachment; filename
      =". $row['name']);
35.
36.                      // Print data
37.                      echo $row['data'];
38.                  }
39.                  else {
40.                      echo 'Error! No image exists with that ID.';
41.                  }
42.
43.                  // Free the mysqli resources
44.                  @mysqli_free_result($result);
45.         }
46.         else {
47.             echo "Error! Query failed: <pre>{$dbLink-
    >error}</pre>";
48.         }
49.         @mysqli_close($dbLink);
50.    }
          51.}
          52.else {
          53.    echo 'Error! No ID was passed.';
          54.}
          55.?>


Any decent browser should be able to read the headers and understand what type of file this
is, and that it is to be downloaded, not opened.

The finish line
So, as you see, this is not as complex as one might think.

This code is of course only written for demonstration purposes and I would not recommend
using it without adding a little extra security. Un-edited, this code would basically allow
anybody to upload anything to your server, which is not a good idea!

I hope this has been helpful, and I wish you all the best.

See you around,
- Atli Þór

Revisions

    •    August 20th, 2008 - Replaced the old mysql functions with the improved mysqli
         functions.
    •    December 12th, 2009 - Updated the introduction to include a bit more detail on the
         pros and cons of this method. Also improved the code structure a bit. Replaced the
         mysqli procedural functions with their OOP counterparts. (Thanks to kovik for
         pointing out the need for these changes!)

Nov 23 '07 #1

More Related Content

Recently uploaded

Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 

Recently uploaded (20)

Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 

Featured

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by HubspotMarius Sescu
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTExpeed Software
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsPixeldarts
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfmarketingartwork
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 

Featured (20)

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 

Uploading files into a my sql database using php

  • 1. Uploading files into a MySQL database using PHP Atli You may be wondering why you would want to put your files “into” the database, rather than just onto the file-system. Well, most of the time, you wouldn’t. In situations where your PHP application needs to store entire files, the preferred method is to save the file onto the server’s file-system, and store the physical location of the file in your database. This is generally considered to be the easiest and fastest way to store files. However, you may find yourself in situations where you would want to keep the file itself with the other data in your database. This gives you - or rather: MySQL - complete control over the file data, rather than just the location of the file on the server. There are some downsides to this method though, such as; decreased performance and added complexity to both your PHP code and your database structure. This is something you should carefully consider before using this in a real-life application. Having said that, this article demonstrates how you can upload a file from a browser into MySQL, and how to send the files back to the browser. Before you start To get through this smoothly, you should be familiar with the following: • PHP Basics • MySQL Basics • Using MySQL in PHP (mysqli) • HTML Forms and how to handle POST data in PHP. The battle plan As with all programs, before we start writing we need to plan a little ahead. Just so we know what we are going to write before we write it. Before we start on the program, we need to design the database. This is not a complex design, as we are not talking about creating some complex filing system. We only need a single table, containing a BLOB field for our file and various other fields to store information on our file, such as name, size, type. Now then. The first phase of the program is getting the file from our users onto the server where our PHP can interact with it. This is the simplest part of the process, requiring only a basic HTML form.
  • 2. The second phase involves reading the uploaded file, making sure it was uploaded successfully and adding it to the database. This is a similar process as the one used when uploading a file to the file-system, but using the MySQL functions rather than the file-system functions. The third phase is to list all files that have been uploaded and saved on the database, with a link so it can be downloaded. The only problem here would be the fact that the file does not exists on the server, so how do we create a link to it? That is a problem handled by phase 4, all we need to do in phase 3 is create a link with the ID of the file to be downloaded embedded in the URL. The fourth, and final, part is the one that is most confusing about this process. The part where we fetch the file and send it to the client's browser. We start by using the MySQL functions, and the ID sent by phase 3, to fetch the file data from the database. Then we set a few headers, letting the browser know what to expect, before finally sending the contents of the file. Now, using this summary as a guide, lets start writing our program. Phase 0: Building a database The database is simple. One table with a BLOB field for the file data and a few fields for various pieces of information relating to the file: Expand|Select|Wrap|Line Numbers 1. CREATE TABLE `file` ( 2. `id` Int Unsigned Not Null Auto_Increment, 3. `name` VarChar(255) Not Null Default 'Untitled.txt', 4. `mime` VarChar(50) Not Null Default 'text/plain', 5. `size` BigInt Unsigned Not Null Default 0, 6. `data` MediumBlob Not Null, 7. `created` DateTime Not Null, 8. PRIMARY KEY (`id`) 9. ) 10. As you see, we store the file name, including the extension. We have the mime type, which we use to let the browser know what kind of file we are dealing with. The size of the file in bytes. And finally the data itself, in a MediumBlob field. Phase 1: Uploading the file Now, we need to get the file from the user. The table we designed does not require any
  • 3. additional information from the user, so we will make this simple and create a HTML form with only a single "file" input field and a submit button: Expand|Select|Wrap|Line Numbers 1. <!DOCTYPE html> 2. <head> 3. <title>MySQL file upload example</title> 4. <meta http-equiv="content-type" content="text/html; charset=U TF-8"> 5. </head> 6. <body> 7. <form action="add_file.php" method="post" enctype="multipart/ form-data"> 8. <input type="file" name="uploaded_file"><br> 9. <input type="submit" value="Upload file"> 10. </form> 11. <p> 12. <a href="list_files.php">See all files</a> 13. </p> 14.</body> 15.</html> Note the third attribute of the <form> element, "enctype". This tells the browser how to send the form data to the server. As it is, when sending files, this must be set to "multipart/form- data". If it is set any other way, or not set at all, your file is probably not going to be transmitted correctly. At the bottom, we have a link to the list we will create in phase 3. Phase 2: Add the file to the database In the form we built in phase 1, we set the action property to "add_file.php". This is the file we are going to build it this phase of the process. This file needs to check if a file has been uploaded, make sure it was uploaded without errors, and add it to the database: Expand|Select|Wrap|Line Numbers 1. <?php 2. // Check if a file has been uploaded 3. if(isset($_FILES['uploaded_file'])) { 4. // Make sure the file was sent without errors 5. if($_FILES['uploaded_file']['error'] == 0) { 6. // Connect to the database 7. $dbLink = new mysqli('127.0.0.1', 'user', 'pwd', 'myTable');
  • 4. 8. if(mysqli_connect_errno()) { 9. die("MySQL connection failed: ". mysqli_connect_error()); 10. } 11. 12. // Gather all required data 13. $name = $dbLink->real_escape_string($_FILES['uploaded_file'] ['name']); 14. $mime = $dbLink->real_escape_string($_FILES['uploaded_file'] ['type']); 15. $data = $dbLink->real_escape_string(file_get_contents($_FILES ['uploaded_file']['tmp_name'])); 16. $size = intval($_FILES['uploaded_file']['size']); 17. 18. // Create the SQL query 19. $query = " 20. INSERT INTO `file` ( 21. `name`, `mime`, `size`, `data`, `created` 22. ) 23. VALUES ( 24. '{$name}', '{$mime}', {$size}, '{$data}', NOW() 25. )"; 26. 27. // Execute the query 28. $result = $dbLink->query($query); 29. 30. // Check if it was successfull 31. if($result) { 32. echo 'Success! Your file was successfully added!'; 33. } 34. else { 35. echo 'Error! Failed to insert the file' 36. . "<pre>{$dbLink->error}</pre>"; 37. } 38. } 39. else { 40. echo 'An error accured while the file was being uploaded. ' 41. . 'Error code: '. intval($_FILES['uploaded_file'] ['error']); 42. } 43. 44. // Close the mysql connection 45. $dbLink->close(); 46. } 47. else { 48. echo 'Error! A file was not sent!'; 49. } 50.
  • 5. 51. // Echo a link back to the main page 52. echo '<p>Click <a href="index.html">here</a> to go back</p>'; 53. ?> 54. Phase 3: Listing all existing files So, now that we have a couple of files in our database, we need to create a list of files and link them so they can be downloaded: Expand|Select|Wrap|Line Numbers 1. <?php 2. // Connect to the database 3. $dbLink = new mysqli('127.0.0.1', 'user', 'pwd', 'myTable'); 4. if(mysqli_connect_errno()) { 5. die("MySQL connection failed: ". mysqli_connect_error()); 6. } 7. 8. // Query for a list of all existing files 9. $sql = 'SELECT `id`, `name`, `mime`, `size`, `created` FROM `file `'; 10.$result = $dbLink->query($sql); 11. 12.// Check if it was successfull 13.if($result) { 14. // Make sure there are some files in there 15. if($result->num_rows == 0) { 16. echo '<p>There are no files in the database</p>'; 17. } 18. else { 19. // Print the top of a table 20. echo '<table width="100%"> 21. <tr> 22. <td><b>Name</b></td> 23. <td><b>Mime</b></td> 24. <td><b>Size (bytes)</b></td> 25. <td><b>Created</b></td> 26. <td><b>&nbsp;</b></td> 27. </tr>'; 28. 29. // Print each file 30. while($row = $result->fetch_assoc()) { 31. echo " 32. <tr> 33. <td>{$row['name']}</td> 34. <td>{$row['mime']}</td> 35. <td>{$row['size']}</td> 36. <td>{$row['created']}</td>
  • 6. 37. <td><a href='get_file.php? id={$row['id']}'>Download</a></td> 38. </tr>"; 39. } 40. 41. // Close table 42. echo '</table>'; 43. } 44. 45. // Free the result 46. $result->free(); 47.} 48.else 49.{ 50. echo 'Error! SQL query failed:'; 51. echo "<pre>{$dbLink->error}</pre>"; 52.} 53. 54.// Close the mysql connection 55.$dbLink->close(); 56.?> Phase 4: Downloading a file This part is the one that usually causes the most confusion. To really understand how this works, you must understand how your browser downloads files. When a browser requests a file from a HTTP server, the server response will include information on what exactly it contains. These bits of information are called headers. The headers usually include information on the type of data being sent, the size of the response, and in the case of files, the name of the file. There are of course a lot of other headers, which I will not cover here, but it is worth looking into! Now, this code. We start simply by reading the ID sent by the link in phase 3. If the ID is valid, we fetch the information on the file who's ID we received, send the headers, and finally send the file data: Expand|Select|Wrap|Line Numbers 1. <?php 2. // Make sure an ID was passed 3. if(isset($_GET['id'])) { 4. // Get the ID 5. $id = intval($_GET['id']); 6.
  • 7. 7. // Make sure the ID is in fact a valid ID 8. if($id <= 0) { 9. die('The ID is invalid!'); 10. } 11. else { 12. // Connect to the database 13. $dbLink = new mysqli('127.0.0.1', 'user', 'pwd', 'myTable '); 14. if(mysqli_connect_errno()) { 15. die("MySQL connection failed: ". mysqli_connect_error ()); 16. } 17. 18. // Fetch the file information 19. $query = " 20. SELECT `mime`, `name`, `size`, `data` 21. FROM `file` 22. WHERE `id` = {$id}"; 23. $result = $dbLink->query($query); 24. 25. if($result) { 26. // Make sure the result is valid 27. if($result->num_rows == 1) { 28. // Get the row 29. $row = mysqli_fetch_assoc($result); 30. 31. // Print headers 32. header("Content-Type: ". $row['mime']); 33. header("Content-Length: ". $row['size']); 34. header("Content-Disposition: attachment; filename =". $row['name']); 35. 36. // Print data 37. echo $row['data']; 38. } 39. else { 40. echo 'Error! No image exists with that ID.'; 41. } 42. 43. // Free the mysqli resources 44. @mysqli_free_result($result); 45. } 46. else { 47. echo "Error! Query failed: <pre>{$dbLink- >error}</pre>"; 48. } 49. @mysqli_close($dbLink);
  • 8. 50. } 51.} 52.else { 53. echo 'Error! No ID was passed.'; 54.} 55.?> Any decent browser should be able to read the headers and understand what type of file this is, and that it is to be downloaded, not opened. The finish line So, as you see, this is not as complex as one might think. This code is of course only written for demonstration purposes and I would not recommend using it without adding a little extra security. Un-edited, this code would basically allow anybody to upload anything to your server, which is not a good idea! I hope this has been helpful, and I wish you all the best. See you around, - Atli Þór Revisions • August 20th, 2008 - Replaced the old mysql functions with the improved mysqli functions. • December 12th, 2009 - Updated the introduction to include a bit more detail on the pros and cons of this method. Also improved the code structure a bit. Replaced the mysqli procedural functions with their OOP counterparts. (Thanks to kovik for pointing out the need for these changes!) Nov 23 '07 #1