473,378 Members | 1,344 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes and contribute your articles to a community of 473,378 developers and data experts.

Uploading files into a MySQL database using PHP

Atli
5,058 Expert 4TB
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 wouldnt.

In situations where your PHP application needs to store entire files, the preferred method is to save the file onto the servers 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:
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=UTF-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.  
  55.  
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
221 366741
santhanalakshmi
147 100+
hi,

Its uploading to my database.Thanks its working fine.
Apr 12 '10 #101
Hi,

I am having a slight problem when downloading the file.

E.g. the file upload is called Unit 1 Lesson 2.pdf. When i go to download the file, if i choose the 'open' option, Adobe opens fine. If i click on 'save' however, it just saves the file as 'Unit' without the rest of the name and no extension.

Any ideas?

Follow Up: I have noticed that this is only a problem in Firefox. Works perfectly in IE.

My code to display can be found below:

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', '####', '#####', '#####');
  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. ?>
  56.  
May 3 '10 #102
i used the given codes, how to add textbox and it will be save to mysql?
Jul 12 '10 #103
Expand|Select|Wrap|Line Numbers
  1. <FORM METHOD="post" ACTION="add_file.php" ENCTYPE="multipart/form-data"> 
  2.     <INPUT TYPE="hidden" NAME="MAX_FILE_SIZE" VALUE="1000000"> 
  3.     <INPUT TYPE="hidden" NAME="action" VALUE="Upload"> 
  4.      <TABLE BORDER="1" cellspacing="1" cellpadding="3"> 
  5.       <TR> 
  6.        <TD>Teacher ID: </TD> 
  7.        <TD><input name="subjects" size = "66%" /></TD> 
  8.       </TR> 
  9.  
  10.       <TR> 
  11.        <TD>File: </TD> 
  12.        <TD><INPUT type="file" NAME="uploaded_file"></TD> 
  13.       </TR> 
  14.       <TR> 
  15.        <TD COLSPAN="2"><INPUT TYPE="submit" VALUE="Upload"></TD> 
  16.       </TR> 
  17.      </TABLE> 
  18.     </FORM>
Jul 12 '10 #104
what is the supply codes to list_file.php and add_file.php?
Jul 12 '10 #105
add_file.php

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('localhost', '', '', ''); 
  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`, "this is my problem" (`t_id`,) `mime`, `size`, `data`, `created` 
  22.                 ) 
  23.                 VALUES ( 
  24.                     '{$name}', '{$t_id}', '{$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="add_file1.php">here</a> to go back</p>'; 
  53.     ?>
Jul 12 '10 #106
list_file.php

Expand|Select|Wrap|Line Numbers
  1. <?php 
  2. // Connect to the database 
  3.     $dbLink = new mysqli('localhost', '', '', ''); 
  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`, `t_id`, `name`, `mime`, `size`, `created` FROM `file`'; 
  10.     $result = $dbLink->query($sql); 
  11.  
  12.  
  13.     // Check if it was successfull 
  14.     if($result) { 
  15.         // Make sure there are some files in there 
  16.         if($result->num_rows == 0) { 
  17.             echo '<p>There are no files in the database</p>'; 
  18.         } 
  19.         else { 
  20.             // Print the top of a table 
  21.             echo '<table width="100%"> 
  22.                     <tr> 
  23.                         <td><b>Name</b></td> 
  24.                 <td><b>Teacher ID</b></td>
  25.                     <td><b>Mime</b></td> 
  26.                         <td><b>Size (bytes)</b></td> 
  27.                         <td><b>Created</b></td> 
  28.                         <td><b>&nbsp;</b></td> 
  29.                     </tr>'; 
  30.  
  31.             // Print each file 
  32.             while($row = $result->fetch_assoc()) { 
  33.                 echo " 
  34.                     <tr> 
  35.                         <td>{$row['name']}</td> 
  36.                 <td>{$row['t_id']}</td> 
  37.                         <td>{$row['mime']}</td> 
  38.                         <td>{$row['size']}</td> 
  39.                         <td>{$row['created']}</td> 
  40.                         <td><a href='get_file.php?id={$row['id']}'>Download</a></td> 
  41.                 <td><a href='delete_ac.php?id={$row['id']}'>delete</a></td>
  42.                     </tr>"; 
  43.  
  44.             } 
  45.  
  46.             // Close table 
  47.             echo '</table>'; 
  48.         } 
  49.  
  50.         // Free the result 
  51.         $result->free(); 
  52.     } 
  53.     else 
  54.     { 
  55.         echo 'Error! SQL query failed:'; 
  56.         echo "<pre>{$dbLink->error}</pre>"; 
  57.     } 
  58.  
  59.     // Close the mysql connection 
  60. $dbLink->close(); 
  61.     ?>
Jul 12 '10 #107
LiuT
2
Hi,

I am wonder if it will upload pdf files of size 2.13MB (1,238,590 bytes)? Thank you in advance.

Liu
Jul 20 '10 #108
Dormilich
8,658 Expert Mod 8TB
with the necessary code, MySQLi and PDO should be able to.
Jul 20 '10 #109
LiuT
2
Hi Dormilich,

Thank you for the reply. I am new working with mysql and php. I am wonder it is any tutorial in how to do it. Any help will be appreciated and thank you in advance.

Liu
Jul 20 '10 #110
Dormilich
8,658 Expert Mod 8TB
I don’t know any in particular, but the PHP Manual is always a good point to start (like this one)
Jul 20 '10 #111
problem.
Hello
i need a view or download a jpg file stored in database.
I tried a code and it give me a error message :
http://bozita.sk/vystava/get_file.php?id=1

how can i fix it ?
Aug 7 '10 #112
Atli
5,058 Expert 4TB
@anton duric
I'm just getting a 404 error. The file doesn't exist.
Aug 7 '10 #113
I dont know when he upload file (name of folder),
i cannot locate a file in server.
Aug 8 '10 #114
hi Atli.^_^
first thank you for this nice topic..this code is exactly what i need for my project..but i have faced 2 problems.


1. when i upload pdf or doc file and download it ,just strange characters appear such as ""TtAKLy|,~"
2.Warning: Cannot modify header information - headers already sent by .....error
i have tried all solutions you posted before but it still not working..

am using Apache 2.2
php5
mysql 5.
IE8
hope you can help me in this...
Aug 15 '10 #115
Atli
5,058 Expert 4TB
@lulitta
Hey.

Those would be a text representation of your file data. If your code fails to set the "Content-Type" header, your browser will assume it is receiving a HTML file and just display all the file data as text.

The Waring you posted should tell you where in your code the problem is. Can you post the full warning message here, and the lines in your code that the warning refers to?

You should also check out this article. It explains in detail why you get this warning, the most common causes and ways to work around them.
Aug 16 '10 #116
this is my download_file.php
Expand|Select|Wrap|Line Numbers
  1. <html>
  2. <?php 
  3. // Make sure an ID was passed 
  4. if(isset($_GET['id'])) { 
  5. // Get the ID 
  6.     $id = intval($_GET['id']); 
  7.  
  8.     // Make sure the ID is in fact a valid ID 
  9.     if($id <= 0) { 
  10.         die('The ID is invalid!'); 
  11.     } 
  12.     else { 
  13.         // Connect to the database 
  14.         $dbLink = new mysqli('localhost', '****', '****', '****'); 
  15.         if(mysqli_connect_errno()) { 
  16.             die("MySQL connection failed: ". mysqli_connect_error()); 
  17.         } 
  18.  
  19.         // Fetch the file information 
  20.         $query = " 
  21.             SELECT mime, name, size, data 
  22.             FROM file3 
  23.             WHERE id = {$id}"; 
  24.         $result = $dbLink->query($query); 
  25.  
  26.         if($result) { 
  27.             // Make sure the result is valid 
  28.             if($result->num_rows == 1) { 
  29.             // Get the row 
  30.                 $row = mysqli_fetch_assoc($result); 
  31.  
  32.               header("Content-Type:".$row['FileMime']); 
  33.               header("Content-Length:".$row['FileSize']); 
  34.               header("Content-Disposition:attachment;filename=".$row['FileName']); 
  35.  
  36.                 // Print data 
  37.                 echo $row['data']; 
  38.             } 
  39.             else { 
  40.                 echo 'This project has been deleted.'; 
  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. else { 
  52.     echo 'Error! No ID was passed.'; 
  53. ?>
  54. </html>
it is not different from the one that you posted, just the host,username, password and database name are different ,but i observed when i hide headers it works with plain/text.
and display strange characters with application/pdf ..etc.

these are warnings for the three headers:
Warning: Cannot modify header information - headers already sent by (output started at C:\AppServ\www\download_file.php:2) in C:\AppServ\www\download_file.php on line 32

Warning: Cannot modify header information - headers already sent by (output started at C:\AppServ\www\download_file.php:2) in C:\AppServ\www\download_file.php on line 33

Warning: Cannot modify header information - headers already sent by (output started at C:\AppServ\www\download_file.php:2) in C:\AppServ\www\download_file.php on line 34
archive system is system that save old data in seartin place.
Aug 16 '10 #117
Dormilich
8,658 Expert Mod 8TB
you start your file with <html>, that’s what’s causing the error.
Aug 17 '10 #118
Dormilich i have tried to remove <html><body><head> tags before..but when i try to download any file, only popup window appears with save or open options for php file that am working with..!!! :(
Aug 17 '10 #119
Dormilich
8,658 Expert Mod 8TB
only popup window appears with save or open options for php file that am working with..!!! :(
of course, that’s what line #34 does. force a download.
Aug 17 '10 #120
yes it forces download but when i chose to save or open file just empty file opened..!! if i try to open pdf or doc files just empty file opened but it works with plain/text files..but i need it to work with pdf files :$
Aug 17 '10 #121
Dormilich
8,658 Expert Mod 8TB
then I can only assume that there might be the headers wrong or the file doesn’t exist at the designated location.
Aug 17 '10 #122
hmmm i have checked headers and files..nothing wrong with them..if i have 2 files, pdf and plain text files in the same location..plain text file works but pdf empty page...!!

thanx Dormilich for trying to help ^_^..any another suggestions!!
Aug 17 '10 #123
Dormilich
8,658 Expert Mod 8TB
..any another suggestions!!
not without a demo page.
Aug 17 '10 #124
ropata
1
Great tutorial Atli

I was wanting to be able to add accompanying text along with uploading the file. I get I'd need to add text fields to the form and in sert new fields in the MySql database that would need populating but I can't figure out how I would gather that data in the add_file.php

Cheers

Rob
Aug 25 '10 #125
Would anyone happen to have a link to the older version of this code which doesnt use mysqli?

Much appreciated

Jimmy
Oct 18 '10 #126
Hey Guys i have been in PHP coding for about 6 months and also tried out this very fantastic tutorial of downloading and uploading.... well upload works like charm! but so does download but when i download the file such as doc file or image file i am not able to view and image shows that it is not supported and word shows that it is corrupted or unsupported format! pls i need help! thanking you in advance!
Oct 18 '10 #127
kovik
1,044 Expert 1GB
@Jim Gordon
There's no reason to use mysql_* functions instead of MySQLi.
Oct 18 '10 #128
Atli
5,058 Expert 4TB
@Sagar Joshi
Hey.

If you are getting corrupted files, a likely reason is that PHP is printing errors or warnings into the file. To see those errors you can simply change line #32 in the get_file.php script so it reads: header('Content-Type: text/html');, and then you need to comment out line #34.

This should print the error, along with all the data, into your browser instead of you getting a download dialog. Then you can browse through it and read the errors/warnings being printed.
Oct 19 '10 #129
Nice Code. Thanks to the original author. May your days be long...
Nov 7 '10 #130
Hi Atli,
I you help me change the mysqli to mysql?


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('localhost', 'root', '###', '###');
  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.  
  55.  
Dec 12 '10 #131
Dormilich
8,658 Expert Mod 8TB
I you help me change the mysqli to mysql?
the mysql_* functions are deprecated, thus it would be a waste of time.
Dec 12 '10 #132
I like above code that is very simple and useful
but its giving me error on
db->close();
while uploading the file
Jan 17 '11 #133
Atli
5,058 Expert 4TB
Hey Hasan.
Which file is it, and what exactly does the error say?
Jan 19 '11 #134
Hi,

Instead of phase 4, can I display the files such as images in a page instead from downloading?

Thanks
marifard
Aug 17 '11 #135
dignat
3
Hello Atli,
I used your code and everuthing is fine but I can not read word files properly when download them and pdfs are corrupt.
Cabn you help me , i used headers, but it is not working
Aug 27 '11 #136
dignat
3
hi atli,
i used your code, but i can not read properly msword document after dwnloading it.
Aug 31 '11 #137
hey hi..am new to this php stuff...so please help me..u have some .php files here...how should i compile or execute dis code??? is it automatically executed when it is called in .html page?? and how to make database connections for a .html file?? thanku in advance..
Oct 12 '11 #138
Dormilich
8,658 Expert Mod 8TB
PHP code is neither compiled nor executed. it is automatically processed on a server with PHP installed (given the server is correctly configured). which also means that it doesn’t do anything in a .html page.
Oct 12 '11 #139
when i download file using php script message will be shown:
Object not found!

The requested URL was not found on this server. The link on the referring page seems to be wrong or outdated. Please inform the author of that page about the error.

If you think this is a server error, please contact the webmaster.
Error 404
localhost
10/31/11 09:29:10
Apache/2.2.2 (Win32) DAV/2 mod_ssl/2.2.2 OpenSSL/0.9.8b mod_autoindex_color PHP/5.1.4
Oct 31 '11 #140
Hi

you code works perfect for single file
but how do i modify it to select multiple files and upload it to the server

Thanks
Nov 7 '11 #141
Hello~ I used your codes for self-practice and I encountered a problem when using this code. I was given this warning:

Warning: mysqli::mysqli() [mysqli.mysqli]: (42000/1049): Unknown database 'file' in C:\xampp\htdocs\test5\add_file.php on line 7
MySQL connection failed: Unknown database 'file'

Line 7 of the code:
Expand|Select|Wrap|Line Numbers
  1. $dbLink = new mysqli('localhost', '***', '***', 'file');
I've used the exact same codes as you've posted, the only difference is the user and password for the database. I've already created the 'file' table in my database though, so I'm not sure what was wrong. I'm using php 5.3.8 & MySQL 5.5.16

Maybe the problem lies with me using MySQL instead of MySQLi? Since the codes use MySQLi. Any help or pointers would be much appreciated since I'm really new to this PHP and MySQL thing. ^_^
Nov 14 '11 #142
Dormilich
8,658 Expert Mod 8TB
the fourth parameter is the name of the database on the database server, not that of a table in a database.
Nov 14 '11 #143
Oh! Thank you for pointing that out. ^^'
Nov 14 '11 #144
I have used the code of 'Atli' posted on Nov, 23 2007 to upload the images into the mysql database and it's working fine but i need some more help that is..

how to display image on browser that is stored in mysql database using php code?

Thanks.
Nov 19 '11 #145
hello ..
this is superb...
can you tell me how to delete a file and send through mail
thanks
Dec 22 '11 #146
Hello,
i am using your code for uploading resumes to a database but i need to do a join to like them together. i was wondering if i could get some help on this.
this is my code to link them

Expand|Select|Wrap|Line Numbers
  1. $qr =  "SELECT job_seeker_info.id, job_resume.id ".
  2.  "FROM job_seeker_info, job_resume ".
  3.     "WHERE job_seeker_info.id = job_resume.id, and job_seeker_info.uname = '".$_SESSION['uname']."'"  ;
how can i get the correct id to show on the page for the link?
Jan 19 '12 #147
zaza77
1
there is the error occur after uploading the files..


Warning: mysqli::mysqli() [mysqli.mysqli]: (28000/1045): Access denied for user 'user'@'localhost' (using password: YES) in C:\xampp\htdocs\project open office easy learning\add_file.php on line 7
MySQL connection failed: Access denied for user 'user'@'localhost' (using password: YES)
Mar 9 '12 #148
Hi Atli's,

Great tutorial just wondering could it be possible to demonstrate how to delete files within the list_files.php as I have tried and Dormilich has help me but still could not understand what I am doing wrong.

As I have stated in my post I am a self learning PHP and MYSQL and would love to see a guide from you on this so that I can learn from it and compare my code as well.

thanks
Mar 15 '12 #149
used same code as above but got error as below

Error! Failed to insert the file

Got a packet bigger than 'max_allowed_packet' bytes

how to get rid of this problem, i ma trying to upload 7mb single file
Apr 6 '12 #150

Sign in to post your reply or Sign up for a free account.

Similar topics

5
by: hdf | last post by:
hi i have problems uploading my database using phpmyadmin n i want to load it using the ssh termal in setd of phpmyadmin. can anyone hlp
11
by: menmysql | last post by:
i am getting the following error while connecting mysql database using jsp java.sql.SQLException: Communication link failure: Bad handshake can any one tell what is the actual problem
8
by: menmysql | last post by:
i am not bale to solve this problem since two weeks i am trying to access records from mysql database using jsp. inside this jsp program i wrote all my JDBC code. it is working very nicely and...
9
by: christopher_board | last post by:
Hi all. I am trying to connect to a MySQL Database using PHP on a local machine using locahost. I am using the following code <?php $dbhost = 'localhost'; $dbuser = 'root'; $dbpass =...
1
by: ganeshg | last post by:
Hai All, Please let me know how to insert audio files into mysql database using .net. Thanking you.....
3
by: Suresh P | last post by:
Hi All, I tried to access the mysql database in ODBC using ip address and username/password. It returns, "cannot connect to MySQL server on IP ADDRESS(10060)". This could be related to Firewall...
1
by: nadeenahmed | last post by:
I have Connected to a MySQL Database using a neatbeans editor. Now, I want to use that same database I created earlier on another pc. Can anyone help and tell me how that is done, please? Thank...
6
by: mfaisalwarraich | last post by:
Hi everyone, I am trying to add multiple pinpoint to google map using Lon/Lat. All addresses will be fetched from mysql database using PHP. I have looked at google and searched for it on...
1
by: santhanalakshmi | last post by:
Hi, I wrote some coding, to import excel data in mysql database using PHP Script? But my script, its not all inserting the excel data in mysql database. I don't know, what mistake did i made?...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.