Connecting Tech Pros Worldwide Forums | Help | Site Map

Uploading files into a MySQL database using PHP

Atli's Avatar
Moderator
 
Join Date: Nov 2006
Location: Iceland
Posts: 3,754
#1   Nov 23 '07
Introduction
You may be asking yourself: "Why put files inside my database? Why not just put them on the file-system?".
In most cases, that is exactly what you should do. It's simple, effective, and requires very little effort on your part.

There are, however, some special circumstances that do require a little more complex tactics.
For example, when handling sensitive data, putting the files into a database gives you a little more control over how the data is handled and who has access to it.

This article shows a simple way of putting files into a MySQL table, using PHP.

Before you start
To get through this smoothly, you should be familiar with the following:
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 FileStorage (
  2.   FileID Int Unsigned Not Null Auto_Increment,
  3.   FileName VarChar(255) Not Null Default 'Untitled.txt',
  4.   FileMime VarChar(50) Not Null Default 'text/plain',
  5.   FileSize BigInt Unsigned Not Null Default 0,
  6.   FileData MediumBlob Not Null,
  7.   Created DateTime Not Null,
  8.   PRIMARY KEY (FileID)
  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. <form action="add_file.php" method="post" enctype="multipart/form-data">
  2.     <input type="file" name="uploaded_file" /><br />
  3.     <input type="submit" value="Upload file" />
  4. </form>
  5.  
  6. <p>
  7.     <a href="list_files.php">See all files</a>
  8. </p>
  9.  
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. {
  5.     # Make sure the file was sent without errors
  6.     if($_FILES['uploaded_file']['error'] == 0) 
  7.     {
  8.         # Connect to the database
  9.         $dbLink = mysqli_connect("127.0.0.1", "user", "pwd", "dbName");
  10.         if(mysqli_connect_errno()) {
  11.             die("MySQL connection failed: ". mysqli_connect_error());
  12.         }
  13.  
  14.         # Gather all required data
  15.         $name = mysqli_real_escape_string($dbLink, $_FILES['uploaded_file']['name']);
  16.         $mime = mysqli_real_escape_string($dbLink, $_FILES['uploaded_file']['type']);
  17.         $size = $_FILES['uploaded_file']['size'];
  18.         $data = mysqli_real_escape_string($dbLink, file_get_contents($_FILES  ['uploaded_file']['tmp_name']));
  19.  
  20.         # Create the SQL query
  21.         $query = "
  22.             INSERT INTO FileStorage (
  23.                 FileName, FileMime, FileSize, FileData, Created
  24.             )
  25.             VALUES (
  26.                 '{$name}', '{$mime}', {$size}, '{$data}', NOW()
  27.             )";
  28.  
  29.         # Execute the query
  30.         $result = mysqli_query($dbLink, $query);
  31.  
  32.         # Check if it was successfull
  33.         if($result) 
  34.         {
  35.             echo "Success! Your file was successfully added!";
  36.         }
  37.         else 
  38.         {
  39.             echo "Error! Failed to insert the file";
  40.             echo "<pre>". mysqli_error($dbLink) ."</pre>";
  41.         }
  42.     }
  43.     else 
  44.     {
  45.         echo "Error! 
  46.                 An error accured while the file was being uploaded. 
  47.                 Error code: ". $_FILES['uploaded_file']['error'];
  48.     }
  49.  
  50.     # Close the mysql connection
  51.     mysqli_close($dbLink);
  52. }
  53. else 
  54. {
  55.     echo "Error! A file was not sent!";
  56. }
  57.  
  58. # Echo a link back to the mail page
  59. echo '<p>Click <a href="index.html">here</a> to go back</p>';
  60. ?>
  61.  
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 = mysqli_connect("127.0.0.1", "user", "pwd", "dbName");
  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. $result = mysqli_query($dbLink, "SELECT FileID, FileName, FileMime, FileSize, Created FROM FileStorage");
  10.  
  11. # Check if it was successfull
  12. if($result) 
  13. {
  14.  
  15.     # Make sure there are some files in there
  16.     if(mysqli_num_rows($result) == 0) {
  17.         echo "<p>There are no files in the database</p>";
  18.     }
  19.     else
  20.     {
  21.         # Print the top of a table
  22.         echo "<table width='100%'><tr>";
  23.         echo "<td><b>Name</b></td>";
  24.         echo "<td><b>Mime</b></td>";
  25.         echo "<td><b>Size (bytes)</b></td>";
  26.         echo "<td><b>Created</b></td>";
  27.         echo "<td><b>&nbsp;</b></td>";
  28.         echo "</tr>";
  29.  
  30.         # Print each file
  31.         while($row = mysqli_fetch_assoc($result))
  32.         {
  33.             # Print file info
  34.             echo "<tr><td>". $row['FileName']. "</td>";
  35.             echo "<td>". $row['FileMime']. "</td>";
  36.             echo "<td>". $row['FileSize']. "</td>";
  37.             echo "<td>". $row['Created']. "</td>";
  38.  
  39.             # Print download link
  40.             echo "<td><a href='get_file.php?id=". $row['FileID'] ."'>Download</a></td>";
  41.             echo "</tr>";
  42.         }
  43.  
  44.         # Close table
  45.         echo "</table>";
  46.     }
  47.  
  48.     # Free the result
  49.     mysqli_free_result($result);
  50. }
  51. else 
  52. {
  53.     echo "Error! SQL query failed:";
  54.     echo "<pre>". $dbLink->error ."</pre>";
  55. }
  56.  
  57. # Close the mysql connection
  58. mysqli_close($dbLink);
  59. ?>
  60.  
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. {
  5.     # Get the ID
  6.     $id = $_GET['id'];
  7.  
  8.     # Make sure the ID is in fact a valid ID
  9.     if(!is_numeric($id) || ($id <= 0)) {
  10.         die("The ID is invalid!");
  11.     }
  12.  
  13.     # Connect to the database
  14.     $dbLink = mysqli_connect("127.0.0.1", "user", "pwd", "dbName");
  15.     if(mysqli_connect_errno()) {
  16.         die("MySQL connection failed: ". mysqli_connect_error());
  17.     }
  18.  
  19.     # Fetch the file information
  20.     $query = "
  21.         SELECT FileMime, FileName, FileSize, FileData 
  22.         FROM fileStorage 
  23.         WHERE FileID = {$id}";
  24.  
  25.     $result = @mysqli_query($dbLink, $query)
  26.         or die("Error! Query failed: <pre>". mysqli_error($dbLink) ."</pre>");
  27.  
  28.     # Make sure the result is valid
  29.     if(mysqli_num_rows($result) == 1)
  30.     {
  31.         # Get the row
  32.         $row = mysqli_fetch_assoc($result);
  33.  
  34.         # Print headers
  35.         header("Content-Type: ". $row['FileMime']);
  36.         header("Content-Length: ". $row['FileSize']);
  37.         header("Content-Disposition: attachment; filename=". $row['FileName']);
  38.  
  39.         # Print data
  40.         echo $row['FileData'];
  41.     }
  42.     else
  43.     {
  44.         echo "Error! No image exists with that ID.";
  45.     }
  46.  
  47.     # Free the mysqli resources
  48.     @mysqli_free_result($result);
  49.     @mysqli_close($dbLink);
  50.  
  51. }
  52. else
  53. {
  54.     echo "Error! No ID was passed.";
  55. }
  56. ?>
  57.  
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

Edits
  • August 20th, 2008 - Replaced the old mysql functions with the improved mysqli functions.
    In order to keep the code as easy to understand as possible, I still retain the procedural style of the old mysql functions, even tho the mysqli extension provides an OOP version.



ifedi's Avatar
Member
 
Join Date: Jan 2008
Location: Abuja, Nigeria.
Posts: 46
#2   Feb 15 '08

re: Uploading files into a MySQL database using PHP


This whole idea of placing files in database BLOB fields, I get the impression it generally isn't a good idea. At least, it does seem quite unpopular. Could you delve a little into the pros and cons of BLOB versus filesystem options for storage of files on the server.
Thanks.
Ifedi.
Markus's Avatar
Moderator
 
Join Date: Jun 2007
Location: York, England, with wolves.
Posts: 4,949
#3   Mar 11 '08

re: Uploading files into a MySQL database using PHP


Quote:

Originally Posted by ifedi

This whole idea of placing files in database BLOB fields, I get the impression it generally isn't a good idea. At least, it does seem quite unpopular. Could you delve a little into the pros and cons of BLOB versus filesystem options for storage of files on the server.
Thanks.
Ifedi.

I guess it depends on what type of app you're thinking of
Quote:

Originally Posted by grantusmaximus.com

Storing images in a database allows for all of your data to be central stored which is more portable, and easy to replicate. This solution would likely also be easier for taking a point-in-time backup with referential integrity.

Which option you choose would really depend on the type application you’re building in my opinion.

So if you’re building an application with a moderately sized amount of image data, and moderate amount of traffic using a database would be okay as the benefits outway the cost. However if you’re building something like flickr with large amounts of data and high traffic, using the file system would be the advised approach.

I’ve also heard of a combined solution that could provide the best of both world. This is storing your images in the database to gain the benefits there, but also use filesystem caching of these to obtain the performance benefits.

Atli's Avatar
Moderator
 
Join Date: Nov 2006
Location: Iceland
Posts: 3,754
#4   Mar 15 '08

re: Uploading files into a MySQL database using PHP


Hi.

In my mind, the main reason for placing files and images into a database is security and control.

If your files are likely to be accessed very frequently, you may be better of leaving them on the file-system. Fetching them from a database involves a lot of extra overhead which will most likely slow you server down.

If, however, the files you are storing are of a sensitive nature, storing them in a database will give you more control over how they are handled. You could even go as far as splitting them up into multiple fields in multiple tables (even multiple database). It allows you a level of control you will generally not have over you file-system (at least not without jumping through several OS dependent hoops).
Newbie
 
Join Date: May 2008
Location: malaysia
Posts: 10
#5   May 19 '08

re: Uploading files into a MySQL database using PHP


hi atli..it's me again...
this time i want to ask if there is a simple way to remove files that have been uploaded from database?
now i m using ur coding to upload my files ^_^
thank u so much for the coding and advice
Newbie
 
Join Date: Mar 2009
Posts: 6
#6   Mar 24 '09

re: Uploading files into a MySQL database using PHP


I am new using mysql and php. I tried to follow the example and everything works fine but when I try to download a file, I get the following error message:

Error! Query failed:
Table 'FileStorage.fileStorage' doesn't exist

Any idea what I did wrong?

Any help will be appreciated.
TheServant's Avatar
Expert
 
Join Date: Feb 2008
Location: Australia
Posts: 914
#7   Mar 24 '09

re: Uploading files into a MySQL database using PHP


Quote:

Originally Posted by msei View Post

I am new using mysql and php. I tried to follow the example and everything works fine but when I try to download a file, I get the following error message:

Error! Query failed:
Table 'FileStorage.fileStorage' doesn't exist

Any idea what I did wrong?

Any help will be appreciated.

I hate to state the obvious but it sounds like you ahve a typo. Look carefully where the word fileStorage was used. Capitals do make a difference, so make sure you didn't mean FileStorage or filestorage. Otherwise paste your download code if you can't see anything and we'll have a look..
Newbie
 
Join Date: Mar 2009
Posts: 6
#8   Mar 25 '09

re: Uploading files into a MySQL database using PHP


Thank you for the info. It is working now, but I am having a problem when I view the pdf or doc file on the browser, is there a way to do not show as binary, see file attached. I would like it to be download in the desktop instead view it at the browser? Any help will be appreciated

Thank you in advance.
Attached Thumbnails
picture-3.png  
Markus's Avatar
Moderator
 
Join Date: Jun 2007
Location: York, England, with wolves.
Posts: 4,949
#9   Mar 25 '09

re: Uploading files into a MySQL database using PHP


Quote:

Originally Posted by msei View Post

Thank you for the info. It is working now, but I am having a problem when I view the pdf or doc file on the browser, is there a way to do not show as binary, see file attached. I would like it to be download in the desktop instead view it at the browser? Any help will be appreciated

Thank you in advance.

Part 4 of the above article shows you how to download a file.
Newbie
 
Join Date: Mar 2009
Posts: 6
#10   Mar 26 '09

re: Uploading files into a MySQL database using PHP


Thanks for the info.
Banned
 
Join Date: Mar 2009
Posts: 1
#11   Mar 27 '09

re: Uploading files into a MySQL database using PHP


Oh, thanks,my friend, !
Newbie
 
Join Date: Apr 2009
Posts: 3
#12   Apr 25 '09

re: Uploading files into a MySQL database using PHP


hello;
dose any one can help me?? I found the above code perfect but the thing I would like to know is how can I save the changes that going to be made to the file that been opened? For example... if word file is being open and any thing is changed in it how to save this changes again in mysql db :((
HEEEEELP
Atli's Avatar
Moderator
 
Join Date: Nov 2006
Location: Iceland
Posts: 3,754
#13   May 5 '09

re: Uploading files into a MySQL database using PHP


Quote:

Originally Posted by tweeengl View Post

hello;
dose any one can help me?? I found the above code perfect but the thing I would like to know is how can I save the changes that going to be made to the file that been opened? For example... if word file is being open and any thing is changed in it how to save this changes again in mysql db :((
HEEEEELP

Hi.

To do that, you would have to update the existing row in the database with the new data.

You could modify the code in phase 2, replacing the INSERT query with an UPDATE query.
Newbie
 
Join Date: Apr 2009
Posts: 3
#14   May 9 '09

re: Uploading files into a MySQL database using PHP


thanx very much for your answer but the problem is still the same because cant take the file new changes after being edit I cant take the new size and new data to be able to update them as they have been inserted at the first place :'(
if you can clear that up to me it would be a great help

thanx again
Atli's Avatar
Moderator
 
Join Date: Nov 2006
Location: Iceland
Posts: 3,754
#15   May 14 '09

re: Uploading files into a MySQL database using PHP


The process of updating a file, stored in the manner the article describes, is almost exactly the same as uploading a new file.

If you want to open, edit, and save a Word document stored in a MySQL database, the file would have to be:
  1. Downloaded to a client (Phase #4), where it would be edited.
  2. Uploaded to server again. (Phase #1)
  3. And finally inserted into the database again. (Phase #2, substituting the INSERT command with a UPDATE command).
The only difference between adding a new file and updating an existing one is that in Phase #2, rather than using INSERT to add a new row, you use UPDATE to alter an existing one.

That would of course require the client to pass along the ID of the old row, so it could be updated. You could simply add that to the form in Phase #1, which you would then use in Phase #2 in the UPDATE command.
Newbie
 
Join Date: Apr 2009
Posts: 3
#16   May 14 '09

re: Uploading files into a MySQL database using PHP


Thanks very much alti for you respond it was great help for me :))
Newbie
 
Join Date: Jun 2009
Posts: 26
#17   Jun 9 '09

re: Uploading files into a MySQL database using PHP


Hi, I am a newbie here in bytes forum.

I exactly follow the whole script you post, from phase 0 to phase 4. Fortunately there was no error and the codes works fine from phase 0 to phase 3. I have a problem in downloading. When I hit the download link, an error occur.

Here's the error..

Quote:
Warning: Cannot modify header information - headers already sent by (output started at c:\Inetpub\wwwroot\uploadingfiles\ddl.php:10) in c:\Inetpub\wwwroot\uploadingfiles\ddl.php on line 42

Warning: Cannot modify header information - headers already sent by (output started at c:\Inetpub\wwwroot\uploadingfiles\ddl.php:10) in c:\Inetpub\wwwroot\uploadingfiles\ddl.php on line 43

Warning: Cannot modify header information - headers already sent by (output started at c:\Inetpub\wwwroot\uploadingfiles\ddl.php:10) in c:\Inetpub\wwwroot\uploadingfiles\ddl.php on line 44
Another error was, there's no download pop window appear.

What is seem to be the error. Thanks in advance.

Last edited by Atli; Jun 9 '09 at 12:46 PM. Reason: Added the [quote] tags.
Newbie
 
Join Date: Jun 2009
Posts: 20
#18   Jun 9 '09

re: Uploading files into a MySQL database using PHP


hi..
I think you should check the code in the phase 4. Make sure there is no white space before the <?php. It is related to the UTF rules..
Atli's Avatar
Moderator
 
Join Date: Nov 2006
Location: Iceland
Posts: 3,754
#19   Jun 9 '09

re: Uploading files into a MySQL database using PHP


Hi roseple.

ririe is right.
The headers are sent as soon as you start sending content to the browser, at which point you can not alter them (obviously).
If you try, you get that error.

Even a single space before your <?php tags will cause this, as will any echo calls from your scripts.

If there is absolutely no way to avoid sending content before altering the headers, you can use the Output Buffering Control functions to delay sending the content.
Newbie
 
Join Date: Jun 2009
Posts: 26
#20   Jun 10 '09

re: Uploading files into a MySQL database using PHP


Thank you Atli and ririe on your reply.

I just check my codes if there is a white space on my download page. But the error is still the same. It does not raise a file download dialog box.

I don't know what to edit/debug anymore.
Thanks guys..
Newbie
 
Join Date: Jun 2009
Posts: 20
#21   Jun 10 '09

re: Uploading files into a MySQL database using PHP


Roseple, why don't you attach along your download codes here..
so that we can together see and check the codes.Then we will try to find
the errors...
Newbie
 
Join Date: Jun 2009
Posts: 26
#22   Jun 10 '09

re: Uploading files into a MySQL database using PHP


Oh.. oki i will attach the file..

By the way, is mysqli different from mysql?
If i change all mysqli command to mysql, this can cause any problem?
Newbie
 
Join Date: Jun 2009
Posts: 20
#23   Jun 10 '09

re: Uploading files into a MySQL database using PHP


MySQLi is designed to work with MySQL 4.1.3 or higher and gives access to more advanced features in MySQL. It requires PHP 5.0 to use. It also gives you more control because you can change MySQL settings using MySQLi without stopping and starting the MYSQL server.
MySQLi is also the OOP version of MySQL extension. MySQLi supports some things that the old MySQL extension doesn't. A lot of people still use the original MySQL extension vs the new MySQLi extension because MySQLi requires MySQL 4.1.13+ and PHP 5.0.7+. However, they both provide access MySQL features.
Newbie
 
Join Date: Jun 2009
Posts: 26
#24   Jun 10 '09

re: Uploading files into a MySQL database using PHP


Oh I see. But like me who is a newbie programmer, I still used the original MySql extension. So in above code you gave, I change all the mysqli to mysql. You can see on my attached file.
Expand|Select|Wrap|Line Numbers
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  5. <title>Untitled Document</title>
  6. </head>
  7. <body><?php
  8. # Make sure an ID was passed
  9. if(isset($_GET['id']))
  10. {
  11.     # Get the ID
  12.     $id = $_GET['id'];
  13.  
  14.     # Make sure the ID is in fact a valid ID
  15.     if(!is_numeric($id) || ($id <= 0)) {
  16.         die("The ID is invalid!");
  17.     }
  18.  
  19.     # Connect to the database
  20.     $dbLink = mysql_connect("localhost", "root", "777") or die (mysql_error());
  21.         mysql_select_db("filestorage", $dbLink) or die(mysql_error());
  22.  
  23.     # Fetch the file information
  24.     $query = "
  25.         SELECT FileMime, FileName, FileSize, FileData 
  26.         FROM filestorage 
  27.         WHERE FileID = {$id}";
  28.  
  29.     $result = @mysql_query($query,$dbLink)
  30.         or die("Error! Query failed: <pre>". mysqli_error($dbLink) ."</pre>");
  31.  
  32.     # Make sure the result is valid
  33.     if(mysql_num_rows($result) == 1)
  34.     {
  35.         # Get the row
  36.         $row = mysql_fetch_assoc($result);
  37.  
  38.         # Print headers
  39.         header("Content-Type:".$row['FileMime']);
  40.         header("Content-Length:".$row['FileSize']);
  41.         header("Content-Disposition:attachment;filename=".$row['FileName']);
  42.  
  43.         # Print data
  44.         echo $row['FileData'];
  45.     }
  46.     else
  47.     {
  48.         echo "Error! No image exists with that ID.";
  49.     }
  50.  
  51.     # Free the mysqli resources
  52.     @mysql_free_result($result);
  53.     @mysql_close($dbLink);
  54.  
  55. }
  56. else
  57. {
  58.     echo "Error! No ID was passed.";
  59. }
  60. ?>
  61. </body>
  62. </html>
  63.  

Last edited by Atli; Jun 10 '09 at 08:56 AM. Reason: Changed the [quote] tags to [code] tags.
Newbie
 
Join Date: Jun 2009
Posts: 20
#25   Jun 10 '09

re: Uploading files into a MySQL database using PHP


Expand|Select|Wrap|Line Numbers
  1. <?php
  2. # Make sure an ID was passed
  3. if(isset($_GET['id']))
  4. {
  5. # Get the ID
  6. $id = $_GET['id'];
  7.  
  8. # Make sure the ID is in fact a valid ID
  9. if(!is_numeric($id) || ($id <= 0)) {
  10. die("The ID is invalid!");
  11. }
  12.  
  13. # Connect to the database
  14. $dbLink = mysql_connect("localhost", "root", "777") or die (mysql_error());
  15. mysql_select_db("filestorage", $dbLink) or die(mysql_error());
  16.  
  17. # Fetch the file information
  18. $query = "
  19. SELECT FileMime, FileName, FileSize, FileData
  20. FROM filestorage
  21. WHERE FileID = {$id}";
  22.  
  23. $result = @mysql_query($query,$dbLink)
  24. or die("Error! Query failed: <pre>". mysqli_error($dbLink) ."</pre>");
  25.  
  26. # Make sure the result is valid
  27. if(mysql_num_rows($result) == 1)
  28. {
  29. # Get the row
  30. $row = mysql_fetch_assoc($result);
  31.  
  32. # Print headers
  33. header("Content-Type:".$row['FileMime']);
  34. header("Content-Length:".$row['FileSize']);
  35. header("Content-Disposition:attachment;filename=".$row['FileName']);
  36.  
  37. # Print data
  38. echo $row['FileData'];
  39. }
  40. else
  41. {
  42. echo "Error! No image exists with that ID.";
  43. }
  44.  
  45. # Free the mysqli resources
  46. @mysql_free_result($result);
  47. @mysql_close($dbLink);
  48.  
  49. }
  50. else
  51. {
  52. echo "Error! No ID was passed.";
  53. }
  54. ?>

Roseple, you just try use the codes above and delete all those thing...

-----delete-----
Expand|Select|Wrap|Line Numbers
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  5. <title>Untitled Document</title>
  6. </head>
  7. <body>
  8. </body>
  9. </html>
-----delete------

The opening for html, head and all the things are not required for this code.As Atli said the headers are sent as soon as you start sending content to the browser, so you can not alter them. If you put the html codes, the program will assume that the header are already sent. So your actually program cannot running properly and you will get errors.

Last edited by Atli; Jun 10 '09 at 08:56 AM. Reason: Added [code] tags.
Newbie
 
Join Date: Jun 2009
Posts: 26
#26   Jun 10 '09

re: Uploading files into a MySQL database using PHP


Wow, you guys were so great.
It's running properly now. The file download dialog box is now present and I can actually download the file.

Thank you so much.
Newbie
 
Join Date: Jun 2009
Posts: 20
#27   Jun 10 '09

re: Uploading files into a MySQL database using PHP


Ok..congratulation roseple..
Good Luck in your work...
Newbie
 
Join Date: Jun 2009
Posts: 26
#28   Jun 10 '09

re: Uploading files into a MySQL database using PHP


Hi, roseple again.. :)

If I try to upload an mp3, mpeg and pdf file but an error occurred. Is it because of their file size or the code does not support that said file?

Thanks...
Newbie
 
Join Date: Jun 2009
Posts: 20
#29   Jun 10 '09

re: Uploading files into a MySQL database using PHP


well, the code cannot support the mp3 file but it should work for pdf..
Newbie
 
Join Date: Jun 2009
Posts: 26
#30   Jun 10 '09

re: Uploading files into a MySQL database using PHP


Even if I try to increase the maximum file size value, pdf file does not work still.
Newbie
 
Join Date: Jun 2009
Posts: 20
#31   Jun 10 '09

re: Uploading files into a MySQL database using PHP


show me your codes for upload
Newbie
 
Join Date: Jun 2009
Posts: 26
#32   Jun 10 '09

re: Uploading files into a MySQL database using PHP


Oki here's my code.
Expand|Select|Wrap|Line Numbers
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  5. <title>Untitled Document</title>
  6. </head>
  7. <body>
  8. <FORM METHOD="post" ACTION="add_file.php" ENCTYPE="multipart/form-data">
  9. <INPUT TYPE="hidden" NAME="MAX_FILE_SIZE" VALUE="1000000">
  10. <INPUT TYPE="hidden" NAME="action" VALUE="Upload">
  11.  <TABLE BORDER="1" cellspacing="1" cellpadding="3">
  12.   <TR>
  13.    <TD>Subject: </TD>
  14.    <TD><input name="subjects" size = "66%" /></TD>
  15.   </TR>
  16.  
  17.   <TR>
  18.    <TD>Client Name: </TD>
  19.    <TD><input name="clientname" size = "35%" id="clientname" /></TD>
  20.   </TR>
  21.  
  22.   <TR>
  23.    <TD>File: </TD>
  24.    <TD><INPUT type="file" NAME="uploaded_file"></TD>
  25.   </TR>
  26.   <TR>
  27.    <TD COLSPAN="2"><INPUT TYPE="submit" VALUE="Upload"></TD>
  28.   </TR>
  29.  </TABLE>
  30. </FORM>
  31.  
  32.  
  33.  
  34. <?php
  35. # Check if a file has been uploaded
  36. if(isset($_FILES['uploaded_file'])) 
  37. {
  38.     # Make sure the file was sent without errors
  39.     if($_FILES['uploaded_file']['error'] == 0) 
  40.     {
  41.         # Connect to the database
  42.         $dbLink = mysql_connect("localhost", "root", "777") or die (mysql_error());
  43.         mysql_select_db("filestorage", $dbLink) or die(mysql_error());
  44.  
  45.         /*if(mysql_connect()) {
  46.             die("MySQL connection failed: ". mysql_error());
  47.         }*/
  48.  
  49.         # Gather all required data
  50.         $name = mysql_real_escape_string($_FILES['uploaded_file']['name']);
  51.         $mime = mysql_real_escape_string($_FILES['uploaded_file']['type']);
  52.         $size = $_FILES['uploaded_file']['size'];
  53.         $data = mysql_real_escape_string(file_get_contents($_FILES  ['uploaded_file']['tmp_name']));
  54.  
  55.         # Create the SQL query
  56.         $query = "
  57.             INSERT INTO file_upload (
  58.                 FileName, FileMime, FileSize, FileData, subjects, clientname, Created
  59.             )
  60.             VALUES (
  61.                 '{$name}', '{$mime}', {$size}, '{$data}', '{$subjects}','{$clientname}', NOW()
  62.             )";
  63.  
  64.         # Execute the query
  65.         $result = mysql_query($query, $dbLink);
  66.  
  67.         # Check if it was successfull
  68.         if($result) 
  69.         {
  70.             echo "Success! Your file was successfully added!";
  71.         }
  72.         else 
  73.         {
  74.             echo "Error! Failed to insert the file";
  75.             echo "<pre>". mysql_error($dbLink) ."</pre>";
  76.         }
  77.     }
  78.     else 
  79.     {
  80.         echo "Error! 
  81.                 An error accured while the file was being uploaded. 
  82.                 Error code: ". $_FILES['uploaded_file']['error'];
  83.     }
  84.  
  85.     # Close the mysql connection
  86.     mysql_close($dbLink);
  87. }
  88.  
  89. # Echo a link back to the mail page
  90.  
  91. echo "<p><a href='list.php'>Click here to see all Files.</a></p>"; 
  92. ?>
  93. </body>
  94. </html>
  95.  

Last edited by Atli; Jun 10 '09 at 08:57 AM. Reason: Added [code] tags.
Newbie
 
Join Date: Jun 2009
Posts: 20
#33   Jun 10 '09

re: Uploading files into a MySQL database using PHP


I already try your code but there is nothing wrong with it and I can upload the pdf file. What is actually the error come out??
Newbie
 
Join Date: Jun 2009
Posts: 26
#34   Jun 10 '09

re: Uploading files into a MySQL database using PHP


Error! An error accured while the file was being uploaded. Error code: 2
Notice: Undefined variable: dbLink in c:\Inetpub\wwwroot\uploadingfiles\add_file.php on line 86

Warning: mysql_close(): supplied argument is not a valid MySQL-Link resource in c:\Inetpub\wwwroot\uploadingfiles\add_file.php on line 86
Newbie
 
Join Date: Jun 2009
Posts: 20
#35   Jun 10 '09

re: Uploading files into a MySQL database using PHP


what is the code on line 82??
Newbie
 
Join Date: Jun 2009
Posts: 20
#36   Jun 10 '09

re: Uploading files into a MySQL database using PHP


sorry what is the code on line 86??
Newbie
 
Join Date: Jun 2009
Posts: 26
#37   Jun 10 '09

re: Uploading files into a MySQL database using PHP


mysql_close($dbLink); //line 86
Newbie
 
Join Date: Jun 2009
Posts: 26
#38   Jun 10 '09

re: Uploading files into a MySQL database using PHP


That warning and error only appear if pdf file was being uploaded.
Newbie
 
Join Date: Jun 2009
Posts: 20
#39   Jun 10 '09

re: Uploading files into a MySQL database using PHP


As I remember you said that you are using mysql instead of mysqli..
I think you should change and use mysql as I believe mysql does not support dblink. So better you change all to mysqli..Try it first
Newbie
 
Join Date: Jun 2009
Posts: 20
#40   Jun 10 '09

re: Uploading files into a MySQL database using PHP


Sorry I mean you should use mysqli as mysql does not support dblink
Atli's Avatar
Moderator
 
Join Date: Nov 2006
Location: Iceland
Posts: 3,754
#41   Jun 10 '09

re: Uploading files into a MySQL database using PHP


ririe and roseple,

Please use [code] tags when you post you code examples.

[code] code goes here [/code]

Thanks.
Newbie
 
Join Date: Jun 2009
Posts: 20
#42   Jun 10 '09

re: Uploading files into a MySQL database using PHP


Sorry Atli...Next time I will use code tag
Atli's Avatar
Moderator
 
Join Date: Nov 2006
Location: Iceland
Posts: 3,754
#43   Jun 10 '09

re: Uploading files into a MySQL database using PHP


The problem there is explained here. (Error code #2).

Your form has a MAX_FILESIZE field, who's value is to low to upload your files:
Expand|Select|Wrap|Line Numbers
  1. <input type="hidden" name="MAX_FILE_SIZE" value="30000" />
Increase that and it should work again.

Also, the error on line #86 has nothing to do with the fact you are using the old mysql extension.
It's because you open your database connection inside the if statement, so when the upload fails it skips it and goes right to the else clause without ever opening it, where it tries to close it, obviously failing.

Edit,
No, on second glance, the mysql_close call is outside the if/else block altogether.
Move it inside the if statement and that error is fixed. (The one on line #86, anyways)

Last edited by Atli; Jun 10 '09 at 09:09 AM. Reason: I'm still asleep I think :P
Newbie
 
Join Date: Jun 2009
Posts: 26
#44   Jun 10 '09

re: Uploading files into a MySQL database using PHP


Sorry Atli.. next time I will use code tag too.
Newbie
 
Join Date: Jun 2009
Posts: 26
#45   Jun 10 '09

re: Uploading files into a MySQL database using PHP


Atli was right, I move the connection of database outside the if statement and the error regrading mysql_close(); was gone.

In max_file_size.. I put 1 000 000. And pdf file is already working, but some pdf file didn't work. Maybe because they are a too large file. Is 1000000, the maximum file size I can put?
Atli's Avatar
Moderator
 
Join Date: Nov 2006
Location: Iceland
Posts: 3,754
#46   Jun 10 '09

re: Uploading files into a MySQL database using PHP


You can simply remove the max_file_size input if it is giving you problems.
It isn't really needed. PHP has it's own size limits that it uses.

The max_file_size input is mostly to give the browser a chance to prevent a file upload that is known to be to large.
Newbie
 
Join Date: Jun 2009
Posts: 26
#47   Jun 11 '09

re: Uploading files into a MySQL database using PHP


Hi Atli..

Correct me if I'm wrong.

Error Code:2 = large file
Error code:4 = there's no file to upload

And what is the other error user may encounter using the codes above?
Thanks..
Newbie
 
Join Date: Jun 2009
Posts: 26
#48   Jun 11 '09

re: Uploading files into a MySQL database using PHP


Ooops, I got it. Sorry..

You posted that already.

Thanks anyway.
Newbie
 
Join Date: Jun 2009
Posts: 26
#49   Jun 19 '09

re: Uploading files into a MySQL database using PHP


Hi Atli,

Why does the link to the next page of this forum is not visible anymore?

Thanks..
Atli's Avatar
Moderator
 
Join Date: Nov 2006
Location: Iceland
Posts: 3,754
#50   Jun 19 '09

re: Uploading files into a MySQL database using PHP


Quote:

Originally Posted by roseple View Post

Hi Atli,

Why does the link to the next page of this forum is not visible anymore?

Thanks..

I moved some of your posts into their own threads, which made this thread fit into one page again.

Click the "subscriptions" link at the top of the page and you should be able to see them.
Reply