Handling File Uploads

The basis for file uploads lies in a special variety of HTML input element, file, which brings up a file selection dialog in most browsers that allows your visitor to select a file for uploading. You can include this element in a HTML form just like you would any other element—web browsers render it as a text box and a "select" (or "browse") button. When your form is submitted, it will automatically send with it the file.

Here is an example HTML form that allows users to select a file for uploading to your server. Note that we specify enctype in our form in order that our file be transmitted properly, and that the action property of the form is set to point to upload2.php, which we will look at in a moment.

    <form enctype="multipart/form-data" method="post" action="upload2.php">
            Send this file: <input name="userfile" type="file" /><br />
            <input type="submit" value="Send File" />
    </form>

We give the new file element the name userfile. Now, here is the accompanying PHP script, upload2.php, which prints out a little information about the file just uploaded from upload1.php:

    $filename = $_FILES['userfile']['name'];
    $filesize = $_FILES['userfile']['size'];
    print "Received $filename  - its size is $filesize";

If there are file uploads, PHP puts information in the superglobal $_FILES for each one in the form of an array. If you run var_dump() on $_FILES, here is how it will look:

 array(1) { ["fileone"]=> array(5) { ["name"]=> string(14) "Greenstone.bmp" ["type"]=> string(9) ...

Get PHP in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.