Uploading Files


HTML forms also let you upload files, and PHP is up to the task. For example, say that you want to upload a file named message.txtand make this text available to your code:

 No worries. PHP can handle this too. 

To upload files, you have to use a multipart form. How do you create one? You use the HTML <FORM> element's ENCTYPE attribute:

 <FORM     ENCTYPE="multipart/form-data"                 .                 .                 . </FORM> 

Now you're free to specify the name of the script to send the file to, as usual:

 <FORM     ENCTYPE="multipart/form-data"     ACTION="phpfile.php" method="POST">                 .                 .                 . </FORM> 

To actually do the uploading, use an HTML file control, created with an <INPUT TYPE="file"> element:

 <FORM     ENCTYPE="multipart/form-data"     ACTION="phpfile.php" method="POST">     Upload this file: <INPUT NAME="userfile" TYPE="FILE">                 .                 .                 . </FORM> 

Note that in this case we're naming the control "userfile", which will be how we refer to the uploaded filebut not using the $_GET, $_POST, or $_REQUEST arrays. Instead, you use a superglobal (i.e., available to all code) array named $_FILES, which we'll do in the next chunk; our goal will be to display the contents of the uploaded file.

All that's left now is to add a Submit button, as shown in phpfile.html, Example 5-17.

Example 5-17. A file upload control example, phpfile.html
 <HTML>     <HEAD>         <TITLE>             Uploading Files         </TITLE>     </HEAD>     <BODY>         <CENTER>             <H1>                 Uploading Files             </H1>             <FORM                 ENCTYPE="multipart/form-data"                 ACTION="phpfile.php" method="POST">                 Upload this file: <INPUT NAME="userfile" TYPE="FILE" />                 <BR>                 <BR>                 <INPUT TYPE="SUBMIT" VALUE="Send File" />             </FORM>         </CENTER>     </BODY> </HTML> 

The file upload control appears in Figure 5-17; browse to the file you want to upload, which is message.txt in this example, and click the Send File button.

Figure 5-17. An HTML upload control.




    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