Working with File Uploads

thank you very much…got it working now… :slight_smile: 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??

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.

mimetype?? what’s that/?? and the function getmimetype() is it like some default sql function or will i have to write it?

Sorry, guess I got the name of the function wrong, [fphp]mime_content_type[/fphp]

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.

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

Your uploaded file will be something like so:

$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?

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

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

Lastly, you would use the <input type=“file” name=“upload_file” /> element, and then using $_FILES in PHP.

thanks…so instead of if ($_SERVER[“REQUEST_METHOD”] == “POST”), should it be if ($_SERVER[“REQUEST_METHOD”] == “FILE”)???

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.

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?

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

There is no HTML verb “FILE”. All post data is sent via POST. You can check for a file by doing an [FPHP]isset[/FPHP] 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.

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?..

columns:
studentid int(11) part of primary key
name varchar(250) part of primary key
mimetype varchar(20)
file blob

it’s showing this error… Undefined index: upload_file in /home/jharvard/vhosts/localhost/html/upload.php on line 31

<?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"]);
    
?>
    
    

I need to see your upload_form.php template

it’s thus:

<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

Ah, you need to add another attribute to your form.

<form action="upload.php" method="post" enctype="multipart/form-data">