With HTML_QuickForm version 3.1, you can have a consistent look across all your forms and a simplified file upload. This chapter starts with the basics then shows you how to process submitted form data with HTML_QuickForm. (From the book, Essential PHP Tools: Modules, Extensions, and Accelerators, by David Sklar, Apress, 2004, ISBN: 159059280.)
Using HTML Quickform for Form Processing - Processing Submitted Data (Page 11 of 13 )
Displaying a form is only half of the picture. When a user submits a form, you need to validate and process the data entered in all of the form elements. HTML_QuickForm gives you two ways to handle that data: with or without a callback function.
Using a Callback Function
The process() method accepts the name of a callback function that is passed an array of submitted form variables. Call process() when you want to do something with the form data. Like the example at the beginning of the chapter, code that uses HTML_QuickForm often has the following if statement that processes the form if data has been submitted and displays the form otherwise:
// Call the processing function if the submitted form data is valid // Otherwise, display the form if ($form->validate()) { $form->process('praise_book'); } else { $form->display(); }
When you call $form->process('praise_book'), it in turn calls a function named praise_book() and passes it an associative array of submitted form data. The following is an example where the processing callback sends an e-mail message to webmaster@example.com with the subject and body entered in the form:
$form = new HTML_QuickForm('send_email'); $form->addElement('text','subject','Subject: ','size="30" maxlength="128"'); $form->addElement('textarea','body','Message Body: ','rows="10" cols="30"'); $form->addElement('submit','send','Send Message'); if ($form->validate()) { $form->process('send_message'); } else { $form->display(); } function send_message($data) { mail('webmaster@example.com',$data['subject'],$data['body']); print "Your message has been sent."; }
The $data array in send_message() is populated with the submitted form data. The value of the array element with the key subject is the value of the submitted form element subject. The same is true for the other elements in the form: body and send.
By default process() includes information about uploaded files in the array it passes to the callback. To exclude uploaded file-related information, pass process() a second argument of false.
When a file is uploaded via a form, the server saves it in a temporary file. Before opening or processing the uploaded file, you should move it to a separate directory with the moveUploadedFile() method. Using this method protects you from accidentally moving a file that wasn’t uploaded via an HTML form. The moveUploadedFile() method is a method of the file upload form element. To call moveUploadedFile(), first access the form element with getElement() and then pass moveUploadedFile() two arguments: the directory to move the file to and the new filename in the destination directory. This moves the file uploaded via the form element myfile to /tmp/processed.txt:
Take care to use =& with getElement() so that $file is a reference to the appropriate form element and not a copy.
In the array of submitted form data passed to process(), file elements have more information than other input elements. Instead of a scalar value, there’s an array of data about the uploaded file. Table 3-1 lists the elements of this array.
Table 3-1. Uploaded File Information
Array Key
Description
name
Filename on the client
type
MIME type of file
tmp_name
Temporary filename on the server
size
File size
error
Error when uploading, if any
You should treat this information about the uploaded file with some skepticism. The values for name and type come from the browser. They are not calculated by the server. Although most browsers report this data correctly, nothing prevents a malicious user from constructing a file upload form submission that includes false values for this data. If you use the reported name to construct a filename on the server for the uploaded file, filter out strings such as .., /, and \. Table 3-2 lists the possible values for the error array element.
Table 3-2. Upload File Error Codes
Error Code
Description
0
No error; upload successful.
1
The file size is bigger than upload_max_filesize configuration directive.
2
The file size is bigger than MAX_FILE_SIZE form variable.
3
The file was partially uploaded.
4
No file was uploaded.
The following code shows a complete file upload example:
$form = new HTML_QuickForm('uploader');
// File upload needs an element of type "file" $form->addElement('file','uploaded_file','Your File:');
// We want files of 128kbytes or less $max_size = 131072;
// Make sure that a file is uploaded $form->addRule('uploaded_file','Please upload a file','uploadedfile');
// Have HTML_QuickForm test, after the file is uploaded, that it is // less than 128k $form->addRule('uploaded_file','Your file is too big','maxfilesize',$max_size); $form->addElement('submit','save','Send It');
// Tell well-behaved browsers not to allow upload of a file larger than // 128k $form->setMaxFileSize(131072); // Display or process the form if ($form->validate()) { $form->process('move_file'); } else { $form->display(); }
function move_file($data) { global $form;
// Remove backslashes and forward slashes from new filename $new_name = strtr($data['uploaded_file']['name'],'/\\',''); // Remove ".." from new filename $new_name = str_replace('..','',$new_name);
$file =& $form->getElement('uploaded_file'); if ($file->moveUploadedFile('/tmp',$new_name)) { print "The file has been uploaded to /tmp/$new_name."; } else { print "The file could not be uploaded to /tmp/$new_name."; } }
This example puts acceptable uploaded files in the /tmp directory. There are two calls to addRule(), which implement built-in HTML_QuickForm form validation rules. These are explained in more detail in the “Setting Validation Rules” section. The two rules used here are uploadedfile, which ensures that the specified field contains an uploaded file and not other form data, and maxfilesize, which checks the size of an uploaded file against a limit. The call to setMaxFileSize() adjusts the MAX_FILE_SIZE hidden element in the form. As discussed previously, this field is used by well-behaved browsers to prevent an oversized file from being sent with the form submission.
Once a file is uploaded, the example calls the move_file() function to process it. This function massages the supplied filename for the uploaded file to remove special characters and then moves the file into the /tmp directory.
This chapter is from Essential PHP Tools: Modules, Extensions, and Accelerators, by David Sklar, (Apress, 2004, ISBN: 1590592808). Check it out at your favorite bookstore today.