Skip to Main Content
PHP in a Nutshell
book

PHP in a Nutshell

by Paul Hudson
October 2005
Intermediate to advanced content levelIntermediate to advanced
372 pages
11h 35m
English
O'Reilly Media, Inc.
Content preview from PHP in a Nutshell

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) ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe
Learning PHP

Learning PHP

David Sklar

Publisher Resources

ISBN: 0596100671Errata Page