| Working with Form Submissions in PHP |
| Article Index |
|---|
| Working with Form Submissions in PHP |
| Page 2 |
| Page 3 |
| Page 4 |
| Page 5 |
Listing 4.14. Setting Up the HTML to Upload a File via HTTP
<FORM METHOD="POST" ACTION="upload.php" ENCTYPE="multipart/form-data">
<INPUT TYPE="file" NAME="myfile"><BR>
<INPUT TYPE="submit" VALUE="Upload the file">
</FORM>
NOTEA special hidden form widget with the name MAX_FILE_SIZE may be used to specify the maximum file size accepted for the file upload. This size restriction is enforced on the client side and may not work for all clients. This check along with the upload_max_filesize configuration directive should be used. |
When the form in is submitted, the file will be uploaded to the Web server and stored in a temporary directory specified by the upload_tmp_dir php.ini directive. PHP then creates a superglobal variable, $_FILES, and, in this case, populates the $_FILES array with a key myfile. The value of this key is another array populated with information about the file that was uploaded. Specifically, the array stored in $_FILES['myfile'] has the keys shown in .
|
name |
The name of the file as it was on the client machine |
|
type |
The MIME type for the file if known |
|
size |
The size of the uploaded file in bytes |
|
tmp_name |
The temporary name given to the file by PHP when it was uploaded to the server |
|
error |
An integer value representing the error that occurred while uploading the file |
NOTEThe following array keys may or may not contain a value, depending on the circumstances under which the file was uploaded. For instance, the type key may be empty if the browser did not provide any MIME information. |
If an error has occurred during the uploading of the file, $_FILES['myfile']['error'] will be set to an integer representing the error that occurred and representing one of the following constants:
Assuming the file was uploaded successfully, it must be moved from its current location (the temporary directory) to its permanent location. If the file is not moved, it will be deleted when the PHP script's execution is complete.
Because of security issues, prior to moving the file from its temporary location to a new one, the is_uploaded_file() should be used to confirm that the file was actually uploaded through PHP. After the file has been confirmed, the move_uploaded_file() can be used to move the uploaded file from its current location to a new one. To move the file to the destination directory, PHP must also have write permission for that directory. See , "Working with Streams and the File System," for detailed information on the use of file-uploading related functions and working with permissions.








