Skip to main content

By clicking Submit, you agree to the developerWorks terms of use.

The first time you sign into developerWorks, a profile is created for you. Select information in your profile (name, country/region, and company) is displayed to the public and will accompany any content you post. You may update your IBM account at any time.

All information submitted is secure.

  • Close [x]

The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerworks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

By clicking Submit, you agree to the developerWorks terms of use.

All information submitted is secure.

  • Close [x]

Learning PHP, Part 2: Upload files and use XML or JSON to store and display file information

Nicholas Chase is the founder and creator of NoTooMi. In addition to technical writing for large corporations, he has been involved in website development for companies such as Lucent Technologies, Sun Microsystems, Oracle, and the Tampa Bay Buccaneers. He has been a high school physics teacher, a low-level-radioactive waste facility manager, an online science fiction magazine editor, a multimedia engineer, an Oracle instructor, and the chief technology officer of an interactive communications company. He is the author of several books, including XML Primer Plus (Sams 2002).

Summary:  This tutorial is Part 2 of a three-part "Learning PHP" series teaching you how to use PHP through building a simple workflow application. Take this tutorial if you have a basic understanding of PHP and want to learn about uploading files from the browser, sessions, or using PHP to process XML or JSON.

03 Jan 2013 - Nicholas Chase updated content throughout this tutorial to reflect current PHP, XML, and JSON technology.

View more content in this series

Date:  03 Jan 2013 (Published 21 Jun 2005)
Level:  Intermediate PDF:  A4 and Letter (709 KB | 34 pages)Get Adobe® Reader®

Activity:  47286 views
Comments:  

Uploading files

In this section you create an upload form for users to upload and save files in the sample workflow application.

How uploading works

In addition to text information, you can use HTML forms to send documents, and that's how you enable users to add files to the system. Here's how the process works:

  1. Users load a form that enables them to choose a file to upload.
  2. Users submit the form.
  3. The browser sends the file and information about it to the server as part of the request.
  4. The server saves the file in a temporary storage location.
  5. The PHP page processing the form submission moves the file from temporary to permanent storage.

Let's start the process by creating the actual form.


The upload form

The form to upload files is similar to those used for the registration and login pages, with two important exceptions (see Listing 8).


Listing 8. Creating the upload form
<?php
   include("top.txt");
?>

<h3>Upload a file</h3>

<p>You can add files to the system for review by an administrator.
Click <b>Browse</b> to select the file you'd like to upload, 
and then click <b>Upload</b>.</p>

<form action="uploadfile_action.php" method="POST"
      enctype="multipart/form-data">

    <input type="file" name="ufile" \>
    <input type="submit" value="Upload" \>

</form>

<?php
   include("bottom.txt");
?>

The enctype attribute tells the browser that the information it sends must be in a particular format that allows for multiple sections of information rather than just a list of name-value pairs.

The file input provides a box that enables the user to click Browse... and choose the file, as in Figure 4.


Figure 4. Choose a file to upload
Screen capture of how to select a file to upload

Add a link to the file in top.txt (see Listing 9).


Listing 9. Adding the upload form to the interface
...
   <li><a href="#" shape="rect">Home</a></li>
   <li><a href="uploadfile.php" shape="rect">Upload</a></li>
   <li><a href="#" shape="rect">Files</a></li>
                    ...
                

Now you're ready to take a look at the information that gets uploaded.


The uploaded information

When you upload a file through the browser, PHP receives an array of information about it. You can find this information in the $_FILE array, based on the name of the input field. For example, your form has a file input with the name ufile, so all the information about that file is contained in the array $_FILE['ufile'].

This array allows the user to upload multiple files. As long as each of the files has its own name, it will have its own array.

Now, notice "$_FILE" is being called an array. In Part 1 of this series, you had a situation in which an array value was itself an array when you passed multiple form values with the same name for the password. In this case, each value of the $_FILE array is itself an associative array. For example, your ufile file has the following information:

  • $_FILE['ufile']['name']—The name of the file (for example, uploadme.txt)
  • $_FILE['ufile']['type']—The type of the file (for example, image/jpg)
  • $_FILE['ufile']['size']—The size, in bytes, of the file that was uploaded
  • $_FILE['ufile']['tmp_name']—The temporary name and location of the file uploaded on the server
  • $_FILE['ufile']['error']—The error code, if any, that resulted from this upload

Since you know what information should be present, verify whether a file was actually uploaded before you perform any processing.


Check for a file

Before you take any action regarding the file, you need to know whether a file actually was uploaded. Create the action page for this form, uploadfile_action.php, and add the code in Listing 10.


Listing 10. Checking for an uploaded file

<?php

   session_start();

   include("top.txt");

   if(isset($_FILES['ufile']['name'])){
       echo "<p>Uploading: ".$_FILES['ufile']['name']."</p>";
   } else {
       echo "You need to select a file.  Please try again.";
   }

   include("bottom.txt");
?>

If the user hasn't specified a file to upload, $_FILES['ufile']['name'] won't be passed by the browser. (Note that isset() also returns false if the value of a variable is null.

Next you'll save the file.


Save the file

Before you start to save the uploaded file, decide where to put it. Until the file's been approved, you don't want it accessible from the website, so create a directory that's not in the main document root.

In this case, you will use /var/www/hidden/. That's where all your files will go, so it's probably a good idea to define a constant. A constant is like a variable, except that once you set it, you can't change its value. Open scripts.txt and add the following definition (see Listing 11).


Listing 11. Creating a constant

...
}
   define("UPLOADEDFILES", "/var/www/hidden/");
?> 

Now you can use this definition in the upload page, as long as you include scripts.txt in that page, as well (see Listing 12).


Listing 12. Saving the uploaded file


<?php
   include("top.txt");
   include("scripts.txt");

   if(isset($_FILES['ufile']['name'])){
       echo "Uploading: ".$_FILES['ufile']['name']."<br>";

       $tmpName = $_FILES['ufile']['tmp_name']; 
       $newName = UPLOADEDFILES . $_FILES['ufile']['name'];  

       if(!is_uploaded_file($tmpName) ||
                            !move_uploaded_file($tmpName, $newName)){
            echo "FAILED TO UPLOAD " . $_FILES['ufile']['name'] .
                 "<br>Temporary Name: $tmpName <br>";
       } else {
            echo "File uploaded.  Thank you!";
       } 

   } else {
     echo "You need to select a file.  Please try again.";
  }
   include("bottom.txt");
?>

First, get the current location of the file and its temporary name (tmp_name), and determine where you want it to go using the constant you defined. (Notice that constants don't start with $.)

Next, you do two things in the if-then statement. Check to make sure that the file you're trying to move is actually a file that was uploaded to the server, rather than a file such as /etc/passwd that the user tricked you into acting upon. If the is_uploaded_file() function comes back false, then its opposite, !is_uploaded_file(), is true, and PHP moves on to display the error message.

If is_uploaded_file() returns true, which means it is an uploaded file, you can then attempt to move it from its current location to a new location. If that move doesn't work, it returns false, and again the opposite is true, so you display the error message.

In other words, if it's not an uploaded file or you can't move it, you display an error message. Otherwise, you display the success message (see Figure 5).


Figure 5. The success message
Screen capture of a success message

Now that you have the file, you need to record its information for later retrieval.

3 of 10 | Previous | Next

Comments



static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Open source, Linux, XML
ArticleID=133660
TutorialTitle=Learning PHP, Part 2: Upload files and use XML or JSON to store and display file information
publish-date=01032013
author1-email=ibmquestions@nicholaschase.com
author1-email-cc=