Reading Uploaded Files


After you upload a file, you can access it using PHP, but it takes a little extra work. You use the superglobal array $_FILES to handle uploaded files; here are the specific elements you can use and what they mean. Note that the first index is the name of the file upload control, which is "userfile" in the previous chunk:

$_FILES['userfile']['name']. The original name of the file on the user's machine.

$_FILES['userfile']['type']. The MIME type of the file. For example, this could be "image/gif" or "text/plain".

$_FILES['userfile']['size']. The size of the uploaded file, in bytes.

$_FILES['userfile']['tmp_name']. The temporary filename of the file in which the uploaded file was stored on the server.

. The error code associated with this file upload.

When a file has been uploaded, it is stored as a temporary file on the server, and you can access that file as $_FILES['userfile']['tmp_name']. We're going to work with files in more depth in Chapter 6, "Creating Web Forms and Validating User Input," but we'll get a preview of how to do that now. You start by using the fopen function to open the temporary file:

 <?php     $handle = fopen($_FILES['userfile']['tmp_name'], "r");         .         .         . ?> 

You can loop over the lines of text in the file in a while loop that ends when we've reached the end of the file, which we can test with the feof function:

 <?php     $handle = fopen($_FILES['userfile']['tmp_name'], "r");     while (!feof($handle)){         .         .         .     } ?> 

To read lines of text from the file, use the fgets function like this, where we also display the text:

 <?php     $handle = fopen($_FILES['userfile']['tmp_name'], "r");     while (!feof($handle)){         $text = fgets($handle);         echo $text, "<BR>";     } ?> 

All that's left is to close the temporary file with fclose, as shown in phpupload.php, Example 5-18.

Example 5-18. Reading an uploaded file, phpupload.php
 <HTML>     <HEAD>         <TITLE>Retrieving File Data</TITLE>     </HEAD>     <BODY>         <CENTER>             <H1>Retrieving File Data</H1>             <BR>             Here are the contents of the file:             <BR>             <?php                 $handle = fopen($_FILES['userfile']['tmp_name'], "r");                 while (!feof($handle)){                     $text = fgets($handle);                     echo $text, "<BR>";                 }                 fclose($handle);             ?>         </CENTER>     </BODY> </HTML> 

The results appear in Figure 5-18, where we've successfully uploaded the file. Very cool.

Figure 5-18. Reading text from an uploaded file.




    Spring Into PHP 5
    Spring Into PHP 5
    ISBN: 0131498622
    EAN: 2147483647
    Year: 2006
    Pages: 254

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net