Uploading files into a MySQL database using PHP

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Atli
    Recognized Expert Expert
    • Nov 2006
    • 5062

    Originally posted by sachin8289
    used same code as above but got error as below

    Error! Failed to insert the file

    Got a packet bigger than 'max_allowed_pa cket' bytes

    how to get rid of this problem, i ma trying to upload 7mb single file
    This is a configuration issue with MySQL. By default the largest "packet" you can send at one time is 1MB. You need to edit the server's configuration file to allow a bigger packet to be received.

    You can find more details here, in the manual:
    C.5.2.10. Packet too large

    Comment

    • Sushant29
      New Member
      • Aug 2012
      • 5

      hey atli , i tried for downloading all types of files and it works also.
      But the problem is that it does'nt shows the contents/data of that particular file.
      Code:
      <?php
      
      include('config.php');
      $filename=$_GET['fname'];
      $ctype=$_GET['ctype'];
      $size=$_GET['size'];
      /* echo $filename;
      echo $ctype;
      echo $size; */
      $tmp = explode(".",$filename); 
      switch ($tmp[count($tmp)-1]) 
      { 
        case "pdf": $ctype="application/pdf"; break; 
        case "exe": $ctype="application/octet-stream"; break; 
        case "zip": $ctype="application/zip"; break; 
        case "docx": 
        case "doc": $ctype="application/msword"; break; 
        case "csv": 
        case "xls": 
        case "xlsx": $ctype="application/vnd.ms-excel"; break; 
        case "ppt": $ctype="application/vnd.ms-powerpoint"; break; 
        case "gif": $ctype="image/gif"; break; 
        case "png": $ctype="image/png"; break; 
        case "jpeg": 
        case "jpg": $ctype="image/jpg"; break; 
        case "tif": 
        case "tiff": $ctype="image/tiff"; break; 
        case "psd": $ctype="image/psd"; break; 
        case "bmp": $ctype="image/bmp"; break; 
        case "ico": $ctype="image/vnd.microsoft.icon"; break; 
        default: $ctype="application/force-download"; 
      } 
      
      $path=$filename;
       
      header("Pragma: public"); // required 
      header("Expires: 0"); 
      header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); 
      header("Cache-Control: private",false); // required for certain browsers 
      header("Content-Type: $ctype"); 
      header("Content-Disposition: attachment; filename=$path"); 
      header("Content-Transfer-Encoding: binary"); 
      header("Content-Length: ".$size); 
      ob_clean(); 
      flush(); 
      readfile($path);
      ?>
      can you sort with this error.......... ....

      Comment

      • mysqlquery
        New Member
        • Mar 2013
        • 3

        Hello,

        I now this is old script, but this is what I really need.
        Im beginner and I tried to edit this, I want mysql, and everything works fine except 'get_file.php'. It says 'Error! No image exists with that ID.'; I cant get ID
        Please can you help me with this.

        I will paste my code, if you have a time please look into that and help.

        Comment

        • mysqlquery
          New Member
          • Mar 2013
          • 3

          Code:
          <?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 {
                   $dbLink =  $dbLink = mysql_connect("localhost", "root", "") or die (mysql_error());
          
          mysql_select_db("databese1", $dbLink) or die ("Could not connect to database!");
          
                   $query = "
                       SELECT `mime`, `name`, `size`, `data`
                       FROM `file`
                       WHERE `id` = {$id}";
                  // $result = $dbLink->query($query);
           
           $result = mysql_query ($query, $dbLink);
           
                   if($result) {
                       // Make sure the result is valid
                       if($result == 1) {
                           $row = mysql_fetch_assoc($result);
           
                           header("Content-Type: ". $row['mime']);
                           header("Content-Length: ". $row['size']);
                           header("Content-Disposition: attachment; filename=". $row['name']);
           
                           // Print data
                           echo $row['data'];
                       }
                       else {
                           echo 'Error! No image exists with that ID.';
                       }
           
                       // Free the mysqli resources
                       @mysql_free_result($result);
                   }
                   else {
                       echo "Error! Query failed:";
                   }
                   mysql_close($dbLink);
               }
           }
           else {
               echo 'Error! No ID was passed.';
           }
           ?>
          Last edited by acoder; Mar 8 '13, 04:21 PM. Reason: Please use [code] tags when posting code

          Comment

          • Atli
            Recognized Expert Expert
            • Nov 2006
            • 5062

            Hey.

            Line #26 of your code. It should be comparing the number of rows in the result set to the number 1. As it is there, however, it's just comparing the result set reference to 1. Look into the mysql_num_rows function.

            One question though. Why would you downgrade the code to use the old MySQL API, when the original code is already using the more modern MySQLi extension? (Granted, it's old enough to be using the procedural MySQLi functions, and without prepared statements, but still...)

            Comment

            • mysqlquery
              New Member
              • Mar 2013
              • 3

              Thanks for replay, sorry for my poor english.
              Can you suggest me any pagination script that will work on this mysqli script. I tried to use some pagination scripts but it wont work, and same pagination scripts work nice with other upload scripts.

              Comment

              • Ammu
                New Member
                • Aug 2011
                • 78

                I have tried it and works properly
                Thank you so much atli for this useful article.

                Comment

                • strelc
                  New Member
                  • Apr 2013
                  • 1

                  Insert this
                  Code:
                  while (@ob_end_clean());
                  line before
                  Code:
                   header("Content-Disposition: attachment; filename=". $row['name']);
                  and download will work like a charm ...

                  Comment

                  • sundyp krishna
                    New Member
                    • Apr 2013
                    • 1

                    hi, wen i download my file, i cant able to open it.. its get corrupted.. may i knw wat coud be the error.. its wrking for text files.. but not for pdf/image/ppt/doc...

                    Comment

                    • Atli
                      Recognized Expert Expert
                      • Nov 2006
                      • 5062

                      Likely some warning or notice in PHP is being printed into the output. Try opening the corrupt file in a text editor like Notepad (make sure it's not too big, or it'll freeze the editor!) and look for error messages in the binary stuff. The text editor should be able to see the text message in the binary and display it as text.

                      Comment

                      • hanugeek
                        New Member
                        • Jun 2013
                        • 1

                        AWSOME! Thankyou so much for share! The code works..!!

                        Comment

                        • abdulrahim0704
                          New Member
                          • Jun 2013
                          • 3

                          boss , i got this error , where is the problem ? .. for download script only (get_file.php)

                          Warning: Cannot modify header information - headers already sent by (output started at C:\xampp\htdocs \test2\get_file .php:2) in C:\xampp\htdocs \test2\get_file .php on line 33

                          Warning: Cannot modify header information - headers already sent by (output started at C:\xampp\htdocs \test2\get_file .php:2) in C:\xampp\htdocs \test2\get_file .php on line 34

                          Warning: Cannot modify header information - headers already sent by (output started at C:\xampp\htdocs \test2\get_file .php:2) in C:\xampp\htdocs \test2\get_file .php on line 35

                          Code:
                          <?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('127.0.0.1', 'root', '', 'file');
                                  if(mysqli_connect_errno()) {
                                      die("MySQL connection failed: ". mysqli_connect_error());
                                  }
                           
                                  // Fetch the file information
                                  $query = "
                                      SELECT `mime`, `name`, `size`, `data`
                                      FROM `file`
                                      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);
                           
                                          // Print headers
                                         header("Content-Type: ". $row['mime']);
                                         header("Content-Length: ". $row['size']);
                                          header("Content-Disposition: attachment; filename=". $row['name']);
                           
                                          // Print data
                                          echo $row['data'];
                                      }
                                      else {
                                          echo 'Error! No image exists with that ID.';
                                      }
                           
                                      // 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.';
                          }
                          ?>

                          Comment

                          • abdulrahim0704
                            New Member
                            • Jun 2013
                            • 3

                            hanugeek :

                            share with me the download code ?

                            Comment

                            • Atli
                              Recognized Expert Expert
                              • Nov 2006
                              • 5062

                              abdulrahim0704. Those errors indicate that something is being printed before the code starts. Note that NOTHING can be placed before the opening <?php tag in my example code. If there is so much as a space, then what you posted will happen.

                              I've also seen this happen when people try to use Unicode files for their PHP code (UTF-8, specifically), including the BOM (Byte order mark) character. PHP doesn't handle Unicode, so the file must be saved as ASCII. If you are unsure on this point, try installing Notepad++, opening the file, and using the "Encoding" menu to convert the file to ASCII.

                              Comment

                              • abdulrahim0704
                                New Member
                                • Jun 2013
                                • 3

                                Atlii thanks for the help :) now it work perfectly !!!!! awesome ! hahahaha...

                                Comment

                                Working...