Uploading files into a MySQL database using PHP

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • chikodi
    New Member
    • Jun 2013
    • 1

    I need help after i used this code was still getting this errors

    Warning: Cannot modify header information - headers already sent by (output started at /home/zivamaho/public_html/get_file.php:1) in /home/zivamaho/public_html/get_file.php on line 32

    Warning: Cannot modify header information - headers already sent by (output started at /home/zivamaho/public_html/get_file.php:1) in /home/zivamaho/public_html/get_file.php on line 33

    Warning: Cannot modify header information - headers already sent by (output started at /home/zivamaho/public_html/get_file.php:1) in /home/zivamaho/public_html/get_file.php on line 34
    /tmp/phpR9kTog


    this is my code: i used it on cpanel upload but got the above errors. Pls help me out

    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 = mysqli_connect('localhost', 'zivamaho_data', 'hospitality', 'zivamaho_hotel');
                if(mysqli_connect_errno()) {
                    die("MySQL connection failed: ". mysqli_connect_error());
                }
        
                // Fetch the file information
                $query = "
                    SELECT first_name,last_name,email,address,phone,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.';
        }
        ?>
    Last edited by Rabbit; Jun 29 '13, 05:11 AM. Reason: Please use code tags when posting code.

    Comment

    • Atli
      Recognized Expert Expert
      • Nov 2006
      • 5062

      Hey, chikodi. This is the exact same problem abdulrahim0704 was having in the posts above yours. The same advice I gave him applies to you as well.

      Also, use [code] tags when posting code. Otherwise the code is more or less unreadable.

      Comment

      • hadinetcat
        New Member
        • Aug 2013
        • 5

        hi, im getting this error please help me when i upload file
        Error! A file was not sent!

        Comment

        • Atli
          Recognized Expert Expert
          • Nov 2006
          • 5062

          Well, clearly a file isn't being sent. Beyond that I can't say without knowing what you did. Make sure your form is written correctly, specifically the "enctype" attribute on the actual <form> element, and the name of the input elements.

          Comment

          • hadinetcat
            New Member
            • Aug 2013
            • 5

            hi guys, i used the code and its work just fine, but when it come to download pdf file it just print in the screen garbage no errors. also checked no white space no bom characters, i don't know whats going on. im have been trying to solve this for days but couldn't please some help required here.
            "û<؟أشX .VبUضà-ى6?N<}oيز:5¸ `@ô›‎ژHصoءµپ _ز=ح§ƒؤ،l*ô¸ƒ o©#é{‡ّ_ںn ¶*'ًE‏–"ضçَùü ê=،yO©§™ےWد>| x(U§ںً|‡çسzDA! ‚²ـXé¹"üےjآـ›ٌ ُ÷4B/ْA حڈûWش قكƒcôےoîJS¹7ز, ےہƒُژAْ‹}÷(S –PO6$وك_÷*7<ںإ ¾–$¦2}ƒث×ژsهہyô و–>]7x‹r,ھ.Mإ‏¶#‹¼ ـً°÷ڈإpnO ‹ ~؟ش›‹s‎üûx ً ُا’ü[ـ~yدم‰‚ہhE6‎ F×'‹?[كگ9‏¶é¬g?لٍح~ك ِqص´p‏güلéüےc ٹآهx· `>„ے^uِأ*>‡ـa cآھéٌْp@â÷مپے° ؛‹^êi <ءوےظ·à}@ے_“اض اڈpقTC‎ Sp.l$p/بµہ_n,کُ؟êےWّ z،R?دزaس*AْZàR ??[‎l'غlً*كُثq‏ ٌ{ƒnx؟éاµ4°، نعكV$ط*Gْضْـ}~ œ@– :—’?گ9°±ےôç غèôب'ٍَے7*?oZ"¸ é*ًءTدسڈê-ُںد6ےy»Dkvy âآ÷üڈ،½ے‏¾ض5q¢ ¾‘~lOم‎ê×؟ْك×ْp ںھ§à¶–&نـ8مü bGّ‏¯چ†@#¦، §§ْ؟/çز2ھMہْ?Q‎Aـ ƒہoOِچ½Cع~¦3ْپn A$^ق‘ُ ¶üے¼ûYVGاسژ« ¯إے*يا<~*سu+ثپ ù ‎O#ً@¹"كO§معش8 ô¦?e:£ ڈثث‎YٍٍéZ،ƒXYژ £¦ہپoOô؟مè@¹·ُ؟ ´*g²ْt…S`>ں[sُ¨?Okٹب‰²‚ ؟ُ¹¸½يحاوئ×½د´ ½U4ژLq«31V4ynG çM›شI¨؟مپيtDSˆ ء¯س‡==xô رسڈ “‎_>گُٹ9 ?ط²H½¯ù½ى?¯ز uê£êéْ‘ù؟زكںًو قئظ¯& ز`2§…ڑX é 1!§ٌ…م›‚x<*.[هêü×/گ*ئذ ¾،4آy‹’ أ¨\r,dbْ‏ ش ë8?¶؛پ(r ‹PH§ “ا×?ië^خIXـƒè؟ çüة#ü½عهQ›ْ~ €‎snئؤںiJ¥ $بyµحڈ§écد?ï› Kطپا3€ع8Pا1¹”¨r „@b¦چعأR$•=د©W ذڑµ$¯°±û£¢z؛پ +w& ڈَ7ٹŒe²ً,•“‚=0ء #ئfkحè1%—Y]V7Naعرd"هdز2ec ڑj&‚**#‹pذُ¦±œ SRھjj)b|دددگ َé®X5ٌrاWWV¢I‎ Bاًط[ْ{ê—fn\ث7ً œ[#`Y‏زٹھp£‚ڑ4+o شo`"

            Code:
             <?php
            
            
            $company =$_GET['company'];
            
            
            // 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', 'sqldata', 'sqldata', 'balhaf');
                    if(mysqli_connect_errno()) {
                        die("MySQL connection failed: ". mysqli_connect_error());
                    }
            
                    // Fetch the file information
                    $query = "
                        SELECT mime, name, size, data
                        FROM $company
                        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

            • Atli
              Recognized Expert Expert
              • Nov 2006
              • 5062

              hadinetcat, what is the actual Content-Type sent with the request? Use a development tool like Firebug to examine the request and check out exactly what it is. - If it's printing stuff to the screen, it's not setting the headers correctly. Otherwise you'd just end up with a corrupt PDF download.

              Comment

              • hadinetcat
                New Member
                • Aug 2013
                • 5

                Atli, the download work fine in firefox mozilla and google chrome but not in IE 10. i have tried everything i also tried
                Code:
                 if(strstr($_SERVER["HTTP_USER_AGENT"],"MSIE")==false) {
                but not helping.. im still getting garbage when using IE 10.

                Comment

                • Atli
                  Recognized Expert Expert
                  • Nov 2006
                  • 5062

                  Well, garbage begets garbage... :)

                  Seriously though, you have not yet answered the question I posed in my last post. What content type is the browser receiving?! That is the key piece of info needed here. - All the browsers, including IE10, have developer tools that can tell you that. Use them!

                  Also, I don't know what exactly you think that line of code is meant to do, but I can't see any reason why you'd use that in this context. In fact, browser sniffing code is generally a bad idea. It should be avoided at all costs!

                  Comment

                  • hadinetcat
                    New Member
                    • Aug 2013
                    • 5

                    Atli, i used ieHTTPHeaders to examine the header but it show empty in IE 10, also i used Firebug in firefox mozilla it show Content-Type: application/pdf which is working fine, but not in IE 10.. what shell i do next ?? to fix my problem

                    Comment

                    • jdetmold
                      New Member
                      • Sep 2013
                      • 1

                      Thanks for the code!
                      I am however getting the error "file was not sent" very often and only with specific files any idea why? I am currently testing with your code completely unedited with a server on my lan.

                      for example I get this error with any .cr2 file (canon raw image file) some .pdf's

                      I also get "An error accured while the file was being uploaded. Error code: 1" with many files but cant figure out what error code 1 means :(

                      any help would be greatly appreciated!

                      edit: it seems to be any file larger than about 2mb in size that throw one of the two errors so far I cant find any other pattern

                      Comment

                      • Atli
                        Recognized Expert Expert
                        • Nov 2006
                        • 5062

                        The manual entry on uploads should be your first stop. (In fact it's pretty much the result returned by Google when asking it any query about PHP file uploads.) - The very first paragraph in the Common Pitfalls section explain the problem, as does the description of error code 1 in the Error Messages Explained section.

                        Comment

                        • tnshum
                          New Member
                          • Oct 2013
                          • 1

                          I try the code, it works.
                          However, when I try to upload the file up to 1MB, it wil has an error as below:
                          Error! Failed to insert the file
                          MySQL server has gone away
                          I want to know how to upload more than 1MB file to mysql?

                          Comment

                          • shayar
                            New Member
                            • Dec 2008
                            • 1

                            where upload file stored in the computer?

                            Comment

                            • Atli
                              Recognized Expert Expert
                              • Nov 2006
                              • 5062

                              @shayar. To answer that, let me quote you the title of this article:
                              Uploading files into a MySQL database using PHP
                              If you are fuzzy on the above concept - versus the normal method of storing files on the file-system - then I strongly suggest you do not use this technique. It is not something you should do without understanding what it is doing and why it's being done that way.

                              Comment

                              • jp26198926
                                New Member
                                • Dec 2013
                                • 1

                                hi.. thank you for posting this tutorial, in my case it works in almost all files except for fetching the image (jpg format) from database.

                                Comment

                                Working...