SitePoint Sponsor

User Tag List

Page 1 of 2 12 LastLast
Results 1 to 25 of 47
  1. #1
    SitePoint Zealot
    Join Date
    Feb 2013
    Posts
    107
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Working with File Uploads

    thank you very much...got it working now... i was wondering about this, is it possible to store .jpeg .pdf or other file formats in an SQL table ?? assuming i wished to create something...assuming i wanted to add this feature to my site where students could upload stuff for their own future use??

  2. #2
    Hosting Team Leader silver trophybronze trophy
    cpradio's Avatar
    Join Date
    Jun 2002
    Location
    Ohio
    Posts
    5,222
    Mentioned
    153 Post(s)
    Tagged
    0 Thread(s)
    Yes, you would use a blob type in MySQL so it can hold the binary data. You should also store the mimetype of the object (getmimetype()) so you know what mimetype to use when you output the information back out.

  3. #3
    SitePoint Zealot
    Join Date
    Feb 2013
    Posts
    107
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    mimetype?? what's that/?? and the function getmimetype() is it like some default sql function or will i have to write it?

  4. #4
    Hosting Team Leader silver trophybronze trophy
    cpradio's Avatar
    Join Date
    Jun 2002
    Location
    Ohio
    Posts
    5,222
    Mentioned
    153 Post(s)
    Tagged
    0 Thread(s)
    Sorry, guess I got the name of the function wrong, mime_content_type

    The mime type tells you what type of file it is, pdf, image, etc. So when the user asks for the file, you can serve it up properly.

  5. #5
    SitePoint Zealot
    Join Date
    Feb 2013
    Posts
    107
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    i see...could you kindly show me an example on how to use the mime function? may be for a pdf file? or if you knw of some good simple link online, where i can read more

  6. #6
    Hosting Team Leader silver trophybronze trophy
    cpradio's Avatar
    Join Date
    Jun 2002
    Location
    Ohio
    Posts
    5,222
    Mentioned
    153 Post(s)
    Tagged
    0 Thread(s)
    Your uploaded file will be something like so:

    PHP Code:
    $fileuploaded $_FILES['upload_file']['tmp_name'];
    $mimetype mime_content_type($fileuploaded);

    $insert "INSERT INTO files (mimetype, file) VALUES (?, ?)";
    // bind $mimetype and file_get_contents($fileuploaded) accordingly 

  7. #7
    SitePoint Zealot
    Join Date
    Feb 2013
    Posts
    107
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by cpradio View Post
    Your uploaded file will be something like so:

    PHP Code:
    $fileuploaded $_FILES['upload_file']['tmp_name'];
    $mimetype mime_content_type($fileuploaded);

    $insert "INSERT INTO files (mimetype, file) VALUES (?, ?)";
    // bind $mimetype and file_get_contents($fileuploaded) accordingly 

    oh okay, i'm beginning to understand this a little...so assuming i have a file called ruby.pdf , and a table called, may be stdlibrary...will this be right/?

    $fileuploaded = $_FILES['upload_file']['ruby']; /// should this stay as it is??
    $mimetype = mime_content_type($fileuploaded);

    $insert = query("INSERT INTO files (mimetype, file) VALUES (?, ?), $mimetype, $fileuploaded";


    // bind $mimetype and file_get_contents($fileuploaded) accordingly ......... ///sorry i didnt understand this bit, i guess that's something like the command for downloading the file, right??

    2.and how could we implement a field with a browse button, which users can click and browse their computer for files to upload? i assume we're to use $_POST somehow?

  8. #8
    Hosting Team Leader silver trophybronze trophy
    cpradio's Avatar
    Join Date
    Jun 2002
    Location
    Ohio
    Posts
    5,222
    Mentioned
    153 Post(s)
    Tagged
    0 Thread(s)
    No, tmp_name stays as is. See http://php.net/manual/en/reserved.variables.files.php
    You may need to change upload_file to match the name of your input type="file" element in your HTML file.

    The bind reference is to replace the ? in the query with the appropriate values. I believe you were using a query() function, so something along the lines of
    PHP Code:
    query("INSERT INTO files (mimetype, file) VALUES (?, ?)"$mimetypefile_get_contents($fileuploaded)); 
    Lastly, you would use the <input type="file" name="upload_file" /> element, and then using $_FILES in PHP.

  9. #9
    SitePoint Zealot
    Join Date
    Feb 2013
    Posts
    107
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    thanks....so instead of if ($_SERVER["REQUEST_METHOD"] == "POST"), should it be if ($_SERVER["REQUEST_METHOD"] == "FILE")???

  10. #10
    Hosting Team Leader silver trophybronze trophy
    cpradio's Avatar
    Join Date
    Jun 2002
    Location
    Ohio
    Posts
    5,222
    Mentioned
    153 Post(s)
    Tagged
    0 Thread(s)
    That I don't know the answer to, I would assume it would still be POST as data from the form submission will still occur in POST, but PHP will store ALL file related data in $_FILES.

  11. #11
    SitePoint Zealot
    Join Date
    Feb 2013
    Posts
    107
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    okay, i ll try that...but i got stuck in the creation of the new table "file"...will u pls take a look at the attachment?

    CAP.JPG

  12. #12
    Hosting Team Leader silver trophybronze trophy
    cpradio's Avatar
    Join Date
    Jun 2002
    Location
    Ohio
    Posts
    5,222
    Mentioned
    153 Post(s)
    Tagged
    0 Thread(s)
    mimetype should be varchar(20) (as that should be plenty of room).

    As for the primary key question, since you likely want a student to be able to store multiple files, there are a couple of ways to pursue this.
    1) All columns make up the primary key - bad (blob as primary key is not good)
    2) Add a name column and the studentid and name column are your primary keys (so a student can store multiple files so long as they are named differently)
    3) Add a fileid column, set it to auto increment and as the primary key, now all students could store multiple files (including the same file)

    Personally, my vote is option #2

  13. #13
    Keeper of the SFL StarLion's Avatar
    Join Date
    Feb 2006
    Location
    Atlanta, GA, USA
    Posts
    3,748
    Mentioned
    73 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by cpradio View Post
    That I don't know the answer to, I would assume it would still be POST as data from the form submission will still occur in POST, but PHP will store ALL file related data in $_FILES.
    There is no HTML verb "FILE". All post data is sent via POST. You can check for a file by doing an isset on the expected $_FILES entry.
    Never grow up. The instant you do, you lose all ability to imagine great things, for fear of reality crashing in.

  14. #14
    Hosting Team Leader silver trophybronze trophy
    cpradio's Avatar
    Join Date
    Jun 2002
    Location
    Ohio
    Posts
    5,222
    Mentioned
    153 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by StarLion View Post
    There is no HTML verb "FILE". All post data is sent via POST. You can check for a file by doing an isset on the expected $_FILES entry.
    Yeah, I didn't have time to go look it up, so I went with a safe answer. But yes, doing isset on $_FILES is a safe way to detect when files are being uploaded.

  15. #15
    SitePoint Zealot
    Join Date
    Feb 2013
    Posts
    107
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    thanks for the replies, @cpradio, "2) Add a name column and the studentid and name column are your primary keys (so a student can store multiple files so long as they are named differently)" name column?? you mean a 4th column separate from the file------blob one?? and how do i link up that to my initial insert command...because i was assuming the filenames will be preserved for all the files the users upload?...

  16. #16
    Hosting Team Leader silver trophybronze trophy
    cpradio's Avatar
    Join Date
    Jun 2002
    Location
    Ohio
    Posts
    5,222
    Mentioned
    153 Post(s)
    Tagged
    0 Thread(s)
    columns:
    studentid int(11) part of primary key
    name varchar(250) part of primary key
    mimetype varchar(20)
    file blob

  17. #17
    SitePoint Zealot
    Join Date
    Feb 2013
    Posts
    107
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    it's showing this error... Undefined index: upload_file in /home/jharvard/vhosts/localhost/html/upload.php on line 31

    Code:
    <?php
      
       // display errors, warnings, and notices
        ini_set("display_errors", true);
        error_reporting(E_ALL);
    
        // requirements
        require("../includes/constants.php"); 
        require("../includes/functions.php");
       
     
        // enable sessions
         session_start();
         
             // require authentication for most pages
        if (!preg_match("{(?:login|logout|register)\.php$}", $_SERVER["PHP_SELF"]))
        {
            if (empty($_SESSION["id"]))
            {
                redirect("login.php");
            }
        }
        
        render("upload_form.php", ["title" => "Upload your stuff"]);
        
        
        if ($_SERVER["REQUEST_METHOD"] == "POST")
        {
          if(isset($_FILES))
          {
        $fileuploaded = $_FILES['upload_file']['tmp_name'];
        $mimetype = mime_content_type($fileuploaded);
        
        $upload=query("INSERT INTO files (mimetype, file, filename) VALUES (?, ?, ?)", $mimetype, file_get_contents($fileuploaded), $_POST['filename']); 
        
          }
          else
          aplogize("Could not upload file");
        }
        
        
        else
        render("upload_form.php", ["title" => "Upload your stuff"]);
        
    ?>

  18. #18
    Hosting Team Leader silver trophybronze trophy
    cpradio's Avatar
    Join Date
    Jun 2002
    Location
    Ohio
    Posts
    5,222
    Mentioned
    153 Post(s)
    Tagged
    0 Thread(s)
    I need to see your upload_form.php template

  19. #19
    SitePoint Zealot
    Join Date
    Feb 2013
    Posts
    107
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    it's thus:
    Code:
    <h1> <strong> UPLOAD YOUR FILES </strong></h1>
    
    <form action="upload.php" method="post">
        <fieldset>
           <div class="control-group">
                <input autofocus name="filename" placeholder="Enter file name" type="text"/>
            </div>
            <div class="control-group">
            <input type="file" name="upload_file" />
            </div>
            <div class="control-group">
                <button type="submit" class="btn-large btn-custom">Upload</button>
            </div>
        </fieldset>
    </form>

    and in fact, in addition to the first error there are 3 more,,,

    Warning: mime_content_type(): Can only process string or stream arguments in /home/jharvard/vhosts/localhost/html/upload.php on line 32

    file_get_contents(): Filename cannot be empty in /home/jharvard/vhosts/localhost/html/upload.php on line 34

    Unknown column 'filename' in 'field list' in /home/jharvard/vhosts/localhost/includes/functions.php on line 139

  20. #20
    Hosting Team Leader silver trophybronze trophy
    cpradio's Avatar
    Join Date
    Jun 2002
    Location
    Ohio
    Posts
    5,222
    Mentioned
    153 Post(s)
    Tagged
    0 Thread(s)
    Ah, you need to add another attribute to your form.
    Code:
    <form action="upload.php" method="post" enctype="multipart/form-data">

  21. #21
    SitePoint Zealot
    Join Date
    Feb 2013
    Posts
    107
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    enters table now... what was that "enctype"??? and about the download part, how could we display the files for the users to download them later on?

    and i was wondering, could we like impose a size limit to the file upload size, maybe like 10MB?

  22. #22
    Hosting Team Leader silver trophybronze trophy
    cpradio's Avatar
    Join Date
    Jun 2002
    Location
    Ohio
    Posts
    5,222
    Mentioned
    153 Post(s)
    Tagged
    0 Thread(s)
    enctype

    As for imposing a filesize restriction, just get the value of the filesize($uploadedfile) and compare it to 10485760 (10 * 1024 * 1024).

    As listing them, you've created scenarios where you grab the records for a studentid from a table and display them on the page, so just look at those and you'll be fine.

  23. #23
    SitePoint Zealot
    Join Date
    Feb 2013
    Posts
    107
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    right, i was also thinking of doing a similar thing, but the only thing i m not sure about is, will the filenames be clickable if i did a for loop that echos the name from the table( ie. will they download when clicked on)??

  24. #24
    Hosting Team Leader silver trophybronze trophy
    cpradio's Avatar
    Join Date
    Jun 2002
    Location
    Ohio
    Posts
    5,222
    Mentioned
    153 Post(s)
    Tagged
    0 Thread(s)
    Make it a link to a download page, passing the name of the file. The download page would then read the blob column and mime type and generate the appropriate header records to feed the file back to the user.
    http://webdesign.about.com/od/php/ht/force_download.htm

  25. #25
    SitePoint Zealot
    Join Date
    Feb 2013
    Posts
    107
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    hi, i started working on the download part, and i made a couple of files and i'm completely lost now in my own work... this is what i currently understand of my work, i ve got three files, two controllers and a template

    1. download.php controller my main download file containing code similar to what is in this link you gave me http://webdesign.about.com/od/php/ht/force_download.htm....
    my code for this file is thus
    Code:
    <?php
      
       // display errors, warnings, and notices
        ini_set("display_errors", true);
        error_reporting(E_ALL);
    
        // requirements
        require("../includes/constants.php"); 
        require("../includes/functions.php");
       
     
        // enable sessions
         session_start();
         
             // require authentication for most pages
        if (!preg_match("{(?:login|logout|register)\.php$}", $_SERVER["PHP_SELF"]))
        {
            if (empty($_SESSION["id"]))
            {
                redirect("login.php");
            }
        }
    
    $file= query("SELECT * FROM files where studentid= ? AND name = ?", $_SESSION['id'], $row['name']);
    $blob = $file['file'];
    $mimetype = $file['mimetype'];
    
    header("Content-disposition: attachment; filename= $blob");
    header("Content-type: $mimetype");
    readfile("$blob");
    ?>

    **********************************************************************************
    the other two files are concerned with diplaying the forms where students can view the files theyve uploaded and select the ones they wish to download via "dowload.php" file...

    2. dloadfile.php controller

    Code:
    <?php
      
        // display errors, warnings, and notices
        ini_set("display_errors", true);
        error_reporting(E_ALL);
    
        // requirements
        require("../includes/constants.php"); 
        require("../includes/functions.php");
        
        // enable sessions
         session_start();
         
             // require authentication for most pages
        if (!preg_match("{(?:login|logout|register)\.php$}", $_SERVER["PHP_SELF"]))
        {
            if (empty($_SESSION["id"]))
            {
                redirect("login.php");
            }
        }
    
        $rows = query("SELECT * FROM files");
            // render form
           render("dloadfile_form.php", ["title" => "Download", "rows" => $rows]);
         
         
    ?>


    &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
    3. dloadfile_form.php

    Code:
    <h1> <strong> DOWNLOAD FILES </strong></h1>
     
    
    <form action="dloadfile.php" method="post" enctype="multipart/form-data">
        <fieldset>
          <div class="control-group">
                 <?php               
    	                foreach ($rows as $row)	{ ?>
                           
                           <li><?php echo $row['name']; ?></li> 
                         <a href="download.php"> Download file</a>
                              
                       <?php } ?>   
            </div>
        </fieldset>
    </form>

    so what happens at the moment is when i open the dloadfile.php paeg, a list of the files uploaded by the student appears, with a link next to each file "Download file"... but when i click on this link, instead of downloading the file, it downloads a file called download.php... confused...


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •