Getting Information About File Uploads


 printf('<p>Error: %s<br />         Original name: %s<br />         File size: %s<br />         Temporary name: %s<br />         MIME type: %s</p>',   $_FILES['File']['error'],   $_FILES['File']['name'],   $_FILES['File']['size'],   $_FILES['File']['tmp_name'],   $_FILES['File']['type']) 


When uploading files to the web server using <input type="file" />, the HTML form has to fulfill two requirements:

  • The enctype attribute has to be set to "multipart/form-data"

  • The method attribute has to be set to "post"

Without these settings, the file upload does not work. It also does not work if the following information is missing from php.ini:

 file_uploads = On 

But if it does, retrieving information about the file is quite easy: In the (superglobal) array $_FILES, you can find the file upload form field under its name. Then, the following subkeys provide further information about the uploaded file:

  • $_FILES["File"]["error"] Error code (0 in case of success)

  • $_FILES["File"]["name"] Original filename

  • $_FILES["File"]["size"] Size of the file

  • $_FILES["File"]["tmp_name"] Temporary filename where PHP saved the file

  • $_FILES["File"]["type"] The file's MIME type as sent by the client, not reliable

Displaying Information About Uploaded Files (upload.php; excerpt)
 <?php   if (isset($_POST['Submit']) && isset($_FILES    ['File'])) {     printf('<p>Error: %s<br />             Original name: %s<br />             File size: %s<br />             Temporary name: %s<br />             MIME type: %s</p>',       $_FILES['File']['error'],       $_FILES['File']['name'],       $_FILES['File']['size'],       $_FILES['File']['tmp_name'],       $_FILES['File']['type']     );   } else { ?>   <form action="<?php echo $_SERVER['PHP_SELF']; ?>"     method="post" enctype="multipart/form-data">     <input type="file" name="File" />     <input type="submit" name="Submit" value="Submit        form" />   </form> <?php   } ?> 

The preceding code outputs the available file information (see Figure 4.4).

Figure 4.4. Information about the uploaded file.


NOTE

Some caveats apply when working with form fields. There is the possibility to provide a maximum file length for the uploaded files in a hidden form field; however, this check is then executed server-side, so it is definitely better if you do that on your own in your script, using the "type" array subelement.

Also, do not rely on the "name" array subelement because this information (the original filename) can be forged. Even worse, some browsers do not always send the original filename, but the complete path to it. Therefore, always call basename() to extract the filename only.





PHP Phrasebook
PHP Phrasebook
ISBN: 0672328178
EAN: 2147483647
Year: 2005
Pages: 193

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