Section 3.3. Handling Browser Input

Putting It All Together > Handling Browser Input

3.3. Handling Browser Input

Since all of the code goes through the handler.php script, the best way to deal with browser input is by using Smarty dynamic plug-ins. This way, it's easy to control when and how the input is handled.

The following example shows how to handle an HTML form asking the user to submit his name and picture using the POST HTTP method:

<?php // Require the Smarty class library. require_once 'Smarty.class.php'; // Instantiate a Smarty object. $smarty = new Smarty; function acceptUserData($params) {     if ($_SERVER['REQUEST_METHOD'] == 'POST') {         // There should be a sanity check to user input data.         require_once 'lib/User.php';         // PEAR package to handle file uploads.         require_once 'HTTP/Upload.php';         // Instantiate an HTTP_Upload object.         $upload = new HTTP_Upload('en');         // Handle the file upload.         $file = $upload->getFiles('picture');         $file->moveTo('uploads/');         // Associate the file with the user.         User::add($_POST['name'], $file->getProp('name'));     } } // Make the acceptUserData() function from within the Smarty template. $smarty->register_function('acceptUserData', 'acceptUserData'); // Display the template. $smarty->display($_SERVER['SCRIPT_FILENAME']); ?>     

The form.html document gets the input from the user through an HTML form and sends it to the handler script. This is the place where you could write all your client-side form validation logic, before any data is sent to the server:

<html> <body> <form method="POST" action="accept_post.html" enctype="multipart/form-data"> <p> Name:<br /> <input type="text" name="name"/> </p> <p> Picture:<br /> <input type="file" name="picture"> </p> <input type="submit" name="Submit"/> </form> </body> </html>     

The output is then displayed by the accept_post.html template. Notice that the template calls the acceptUserData() function before writing any HTML output:

{acceptUserData} <html> <body> <p> Thank you for sending your picture. </p> </body> </html>

Figure 3-1 represents the entire application flow, from the entry point when an HTTP request is received from the user, up to the end when the template is rendered on the user's web browser.

Notice how things run much faster when the template contents are already cached. That's because the handler doesn't have to generate any data and process the associated templates.

You could even create a cache layer before the request is passed on to the handler script. That would skip the handler script execution altogether, delivering the results immediately.

Figure 3-1. Application flow diagram


 

 



PHP and Smarty on Large-Scale Web Development
PHP and Smarty on Large-Scale Web Development
ISBN: 047008023X
EAN: N/A
Year: 2007
Pages: 20
BUY ON AMAZON

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