Uploading files into a MySQL database using PHP

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • mirasol
    New Member
    • Jul 2010
    • 6

    add_file.php

    Code:
    <?php 
    	// Check if a file has been uploaded 
    	if(isset($_FILES['uploaded_file'])) { 
    	    // Make sure the file was sent without errors 
    	    if($_FILES['uploaded_file']['error'] == 0) { 
    	        // Connect to the database 
    	        $dbLink = new mysqli('localhost', '', '', ''); 
    	        if(mysqli_connect_errno()) { 
    	            die("MySQL connection failed: ". mysqli_connect_error()); 
    	        } 
    	  
    	        // Gather all required data 
    	        $name = $dbLink->real_escape_string($_FILES['uploaded_file']['name']);
    		$mime = $dbLink->real_escape_string($_FILES['uploaded_file']['type']); 
    	        $data = $dbLink->real_escape_string(file_get_contents($_FILES  ['uploaded_file']['tmp_name'])); 
    	        $size = intval($_FILES['uploaded_file']['size']); 
    	  
    	        // Create the SQL query 
    	        $query = " 
    	            INSERT INTO `file` ( 
    	                `name`, "this is my problem" (`t_id`,) `mime`, `size`, `data`, `created` 
    	            ) 
    	            VALUES ( 
    	                '{$name}', '{$t_id}', '{$mime}', {$size}, '{$data}', NOW() 
    	            )"; 
    	  
    	        // Execute the query 
    	        $result = $dbLink->query($query); 
    	  
    	        // Check if it was successfull 
    	        if($result) { 
    	            echo 'Success! Your file was successfully added!'; 
    	        } 
    	        else { 
    	            echo 'Error! Failed to insert the file' 
    	               . "<pre>{$dbLink->error}</pre>"; 
    	        } 
    	    } 
    	    else { 
    	        echo 'An error accured while the file was being uploaded. ' 
    	           . 'Error code: '. intval($_FILES['uploaded_file']['error']); 
    	    } 
    	  
    	    // Close the mysql connection 
    	    $dbLink->close(); 
    	} 
    	else { 
    	    echo 'Error! A file was not sent!'; 
    	} 
    	  
    	// Echo a link back to the main page 
    echo '<p>Click <a href="add_file1.php">here</a> to go back</p>'; 
    	?>
    Last edited by Dormilich; Jul 13 '10, 05:35 AM. Reason: Please use [code] tags when posting code

    Comment

    • mirasol
      New Member
      • Jul 2010
      • 6

      list_file.php

      Code:
      <?php 
      // Connect to the database 
      	$dbLink = new mysqli('localhost', '', '', ''); 
      	if(mysqli_connect_errno()) { 
      	    die("MySQL connection failed: ". mysqli_connect_error()); 
      	} 
      	  
      	// Query for a list of all existing files 
      	$sql = 'SELECT `id`, `t_id`, `name`, `mime`, `size`, `created` FROM `file`'; 
      	$result = $dbLink->query($sql); 
      	  
      
      	// Check if it was successfull 
      	if($result) { 
      	    // Make sure there are some files in there 
      	    if($result->num_rows == 0) { 
      	        echo '<p>There are no files in the database</p>'; 
      	    } 
      	    else { 
      	        // Print the top of a table 
      	        echo '<table width="100%"> 
      	                <tr> 
      	                    <td><b>Name</b></td> 
      				<td><b>Teacher ID</b></td>
                          <td><b>Mime</b></td> 
      	                    <td><b>Size (bytes)</b></td> 
      	                    <td><b>Created</b></td> 
      	                    <td><b>&nbsp;</b></td> 
      	                </tr>'; 
      	  
      	        // Print each file 
      	        while($row = $result->fetch_assoc()) { 
      	            echo " 
      	                <tr> 
      	                    <td>{$row['name']}</td> 
      			    <td>{$row['t_id']}</td> 
      	                    <td>{$row['mime']}</td> 
      	                    <td>{$row['size']}</td> 
      	                    <td>{$row['created']}</td> 
      	                    <td><a href='get_file.php?id={$row['id']}'>Download</a></td> 
      			    <td><a href='delete_ac.php?id={$row['id']}'>delete</a></td>
      	                </tr>"; 
      
      	        } 
      	  
      	        // Close table 
      	        echo '</table>'; 
      	    } 
      	  
      	    // Free the result 
      	    $result->free(); 
      	} 
      	else 
      	{ 
      	    echo 'Error! SQL query failed:'; 
      	    echo "<pre>{$dbLink->error}</pre>"; 
      	} 
      	 
      	// Close the mysql connection 
      $dbLink->close(); 
      	?>
      Last edited by Dormilich; Jul 13 '10, 05:35 AM. Reason: Please use [code] tags when posting code

      Comment

      • LiuT
        New Member
        • Jul 2010
        • 2

        Big File Size

        Hi,

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

        Liu

        Comment

        • Dormilich
          Recognized Expert Expert
          • Aug 2008
          • 8694

          with the necessary code, MySQLi and PDO should be able to.

          Comment

          • LiuT
            New Member
            • Jul 2010
            • 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

            Comment

            • Dormilich
              Recognized Expert Expert
              • Aug 2008
              • 8694

              I don’t know any in particular, but the PHP Manual is always a good point to start (like this one)

              Comment

              • anton duric
                New Member
                • Aug 2010
                • 2

                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 :


                how can i fix it ?

                Comment

                • Atli
                  Recognized Expert Expert
                  • Nov 2006
                  • 5062

                  Originally posted by anton duric
                  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 :


                  how can i fix it ?
                  I'm just getting a 404 error. The file doesn't exist.

                  Comment

                  • anton duric
                    New Member
                    • Aug 2010
                    • 2

                    I don´t know when he upload file (name of folder),
                    i cannot locate a file in server.

                    Comment

                    • lulitta
                      New Member
                      • Aug 2010
                      • 5

                      unicode problem

                      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 ""ºT¨t³AKLÒ y|òµ,~"
                      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...

                      Comment

                      • Atli
                        Recognized Expert Expert
                        • Nov 2006
                        • 5062

                        Originally posted by lulitta
                        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 ""ºT¨t³AKLÒ y|òµ,~"
                        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...
                        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.

                        Comment

                        • lulitta
                          New Member
                          • Aug 2010
                          • 5

                          this is my download_file.p hp
                          Code:
                          <html>
                          <?php 
                          // Make sure an ID was passed 
                          if(isset($_GET['id'])) { 
                          // Get the ID 
                              $id = intval($_GET['id']); 
                            
                              // Make sure the ID is in fact a valid ID 
                              if($id <= 0) { 
                                  die('The ID is invalid!'); 
                              } 
                              else { 
                                  // Connect to the database 
                                  $dbLink = new mysqli('localhost', '****', '****', '****'); 
                                  if(mysqli_connect_errno()) { 
                                      die("MySQL connection failed: ". mysqli_connect_error()); 
                                  } 
                            
                                  // Fetch the file information 
                                  $query = " 
                                      SELECT mime, name, size, data 
                                      FROM file3 
                                      WHERE id = {$id}"; 
                                  $result = $dbLink->query($query); 
                            
                                  if($result) { 
                                      // Make sure the result is valid 
                                      if($result->num_rows == 1) { 
                                      // Get the row 
                                          $row = mysqli_fetch_assoc($result); 
                            
                                        header("Content-Type:".$row['FileMime']); 
                                        header("Content-Length:".$row['FileSize']); 
                                        header("Content-Disposition:attachment;filename=".$row['FileName']); 
                            
                                          // Print data 
                                          echo $row['data']; 
                                      } 
                                      else { 
                                          echo 'This project has been deleted.'; 
                                      } 
                            
                                      // Free the mysqli resources 
                                      @mysqli_free_result($result); 
                                  } 
                                  else { 
                                      echo "Error! Query failed: <pre>{$dbLink->error}</pre>"; 
                                  } 
                                  @mysqli_close($dbLink); 
                              } 
                          } 
                          else { 
                              echo 'Error! No ID was passed.'; 
                          } 
                          ?>
                          </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.p hp:2) in C:\AppServ\www\ download_file.p hp on line 32

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

                          Warning: Cannot modify header information - headers already sent by (output started at C:\AppServ\www\ download_file.p hp:2) in C:\AppServ\www\ download_file.p hp on line 34
                          archive system is system that save old data in seartin place.

                          Comment

                          • Dormilich
                            Recognized Expert Expert
                            • Aug 2008
                            • 8694

                            you start your file with <html>, that’s what’s causing the error.

                            Comment

                            • lulitta
                              New Member
                              • Aug 2010
                              • 5

                              Dormilich i have tried to remove <html><body><he ad> 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..!!! :(

                              Comment

                              • Dormilich
                                Recognized Expert Expert
                                • Aug 2008
                                • 8694

                                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.

                                Comment

                                Working...