In order to upload files from a web page, we must create a means of allowing the user to locate the file they wish to provide us with. As I mentioned in an earlier article, there are two methods of doing so: the HTML5 drag-and-drag method (useful for images and multiple files) and the traditional (and more broadly supported) HTML “browse for file” option. In this entry, we’ll concentrate on the latter.
First, we need a form to take the file, along with any other information the user provides us with. The action
of the form specifies how and where that information is processed. As we expect the user to include more than simple text data, we must enhance the form
tag with an enctype
attribute:
<form method="post" action="uploader.php" enctype="multipart/form-data">
Within the form itself we must provide a means for the user to attach and upload a file. Traditionally, this is achieved by adding a file input:
<input type="file" name="upload" id="upload">
Unlike other form inputs, file
creates its own interface, and does not require a label;
the easiest way to see this is to look at the result in the browser.
Within the form itself, it’s a very good idea to set the upper limit for the maximum file size you will accept. While this setting can be fooled, there are other server-side settings that can’t be… and enforcing a limit at this point helps the majority of users, who will be immediately prevented from uploading files that are too large, rather than wasting time and bandwidth wading through the upload process only to be informed later that their file is too big.
There are three important points about this upper limit: first, it is hidden, i.e. not seen by the user. Second, it must go before the file
input in the HTML code. Lastly, it measures the file size in bytes, where 1KB is equal to 1024 bytes (If you don’t know binary arithmetic, Google will happily do the KB-to-bytes conversion for you).
Let’s say we wanted to limit the user to uploading an image that was no larger than 60K in size. 60K is 61440 bytes, so our form would look like this:
<form method="post" action="uploader.php" enctype="multipart/form-data">
<fieldset>
<input type="hidden" name="MAX_FILE_SIZE" value="61440">
<input type="file" name="upload" id="upload">
<input type="submit" value="Upload">
</fieldset>
</form>
This page would be saved as form.php. Next, we have to work on validating, accepting, and transferring the file the user provided. For ease of comprehension I’ll write formhandler.php as a separate document in the next related entry, although the code could be written, with some small changes, on form.php itself.
While it is totally feasible to make a form that solely exists to upload a file, it is relatively rare and inefficient to do so. Don’t hesitate to ask for other information via standard inputs in the same form; all of it, file and text together, can be processed by PHP.
Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.