Webocreation

Monday, January 4, 2010

File Upload Forms and Scripts

File Upload Forms and Scripts
So far we've looked at simple form input. Browsers Netscape 2 or better and Internet Explorer 4 or better all support file uploads, and so, of course, does PHP. In this section, you will examine the features that PHP makes available to deal with this kind of input.

First, we need to create the HTML. HTML forms that include file upload fields must include an ENCTYPE argument:



ENCTYPE="multipart/form-data"


PHP also works with an optional hidden field that you can insert before the file upload field. It should be called MAX_FILE_SIZE and should have a value representing the maximum size in bytes of the file that you are willing to accept. This size cannot override the maximum size set in the upload_max_filesize field in your php.ini file that defaults to 2MB. The MAX_FILE_SIZE field is obeyed at the browser's discretion, so you should rely upon the php.ini setting to cap unreasonable uploads. After the MAX_FILE_SIZE field is entered, you are ready to add the upload field itself. It is simply an input element with a type argument of "file". You can give it any name you want. Listing 10.11 brings all this work together into an HTML upload form.


$_FILE Elements Element
Contains
Example

$ FILES['fupload']['name']
Name of uploaded file
test.gif

$_FILES['fupload']['tmp_name']
Path to temporary file
/tmp/phprDfZvN

$_FILES['fupload']['size']
Size (in bytes) of uploaded file
6835

$_FILES['fupload']['error']
An error code corresponding to a PHP constant
UPLOAD_ERR_FORM_SIZE

$_FILES['fupload']['type']
MIME type of uploaded file (where given by client)
image/gif



You can use the error element of an element in $_FILES to diagnose the reason for a failed upload. Assuming a file upload named 'fupload', we would find the error code in



$_FILES['fupload']['error]


lists the possible error codes.
$_FILE Error Constants Constant Name


UPLOAD_ERR_OK
0
No problem

UPLOAD_ERR_INI_SIZE
1
File size exceeds php.ini limit set in upload_max_filesize

UPLOAD_ERR_FORM_SIZE
2
File size exceeds limit set in hidden element named MAX_FILE_SIZE

UPLOAD_ERR_PARTIAL
3
File only partially uploaded

UPLOAD_ERR_NO_FILE
4
File was not uploaded



Armed with this information, we can write a quick and dirty script that displays information about uploaded files (see Listing 10.12). If the uploaded file is in GIF format, the script will even attempt to display it.

No comments:

Post a Comment