Team LiB
Previous Section Next Section

Creating the Upload Script

Take a moment to commit the following list to memory—it contains the variables that are automatically placed in the $_FILES superglobal after a successful file upload. The base of img1 comes from the name of the input field in the original form.

Note 

A MIME type indicates the type of the content being transmitted. For instance, the MIME type of a JPEG file is image/jpg, and the MIME type of a Microsoft Word document is application/msword.

The goal of this script is to take the uploaded file, copy it to the document root of the web server, and return a confirmation to the user containing values for all the variables in the preceding list.

  1. Open a new file in your text editor and start a PHP block:

    <?
    
  2. Create an ifelse statement that checks for a value in $_FILES[img1]. if ($_FILES[img1] != "") {

  3. If $_FILES[img1] is not empty, execute the copy function. Use @ before the function name to suppress warnings, and use the die() function to cause the script to end and a message to be displayed if the copy() function fails.

    @copy($_FILES[img1][tmp_name],
    "/usr/local/apache2/htdocs/".$_FILES[img1][name])
         or die("Couldn't copy the file.");
    
    
    
    Note 

    If the document root of your web server is not /usr/local/apache2/htdocs/, as shown in step 3, change the path to match your own system. For example, a Windows user might use /Program Files/Apache Group/Apache/htdocs/.

  4. Continue the else statement to handle the lack of a file for upload:

    } else {
         die("No input file specified");
    
  5. Close the ifelse statement, and then close your PHP block:

    }
    ?>
    
  6. Add this HTML:

    <HTML>
    <HEAD>
    <TITLE>Successful File Upload</TITLE>
    </HEAD>
    <BODY>
    <H1>Success!</H1>
    
  7. Mingle HTML and PHP, printing a line that displays values for the various elements of the uploaded file (name, size, and type):

    <P>You sent: <? echo $_FILES[img1][name]; ?>,
    a <? echo $_FILES[img1][size]; ?> byte file with
    a mime type of <? echo $_FILES[img1][type]; ?>.</P>
    
  8. Add some more HTML so that the document is valid:

    </BODY>
    </HTML>
    
  9. Save the file with the name do_upload.php.

The code should look something like the following figure.

Click To expand

In the next section, you finally get to upload a file!


Team LiB
Previous Section Next Section