PHP CookBook Free Open Book

PHP CookBook

Previous Section Next Section

Recipe 9.4 Working with Multipage Forms

9.4.1 Problem

You want to use a form that displays more than one page and preserve data from one page to the next.

9.4.2 Solution

Use session tracking:

session_start();
$_SESSION['username'] = $_GET['username'];

You can also include variables from a form's earlier pages as hidden input fields in its later pages:

<input type="hidden" name="username" 
       value="<?php echo htmlentities($_GET['username']); ?>">

9.4.3 Discussion

Whenever possible, use session tracking. It's more secure because users can't modify session variables. To begin a session, call session_start( ); this creates a new session or resumes an existing one. Note that this step is unnecessary if you've enabled session.auto_start in your php.ini file. Variables assigned to $_SESSION are automatically propagated. In the Solution example, the form's username variable is preserved by assigning $_GET['username'] to $_SESSION['username'].

To access this value on a subsequent request, call session_start( ) and then check $_SESSION['username']:

session_start( );
$username = htmlentities($_SESSION['username']);
print "Hello $username.";

In this case, if you don't call session_start( ), $_SESSION isn't set.

Be sure to secure the server and location where your session files are located (the filesystem, database, etc.); otherwise your system will be vulnerable to identity spoofing.

If session tracking isn't enabled for your PHP installation, you can use hidden form variables as a replacement. However, passing data using hidden form elements isn't secure because anyone can edit these fields and fake a request; with a little work, you can increase the security to a reliable level.

The most basic way to use hidden fields is to include them inside your form.

<form action="<?php echo $_SERVER['PHP_SELF']; ?>"
      method="get">

<input type="hidden" name="username" 
       value="<?php echo htmlentities($_GET['username']); ?>">

When this form is resubmitted, $_GET['username'] holds its previous value unless someone has modified it.

A more complex but secure solution is to convert your variables to a string using serialize( ), compute a secret hash of the data, and place both pieces of information in the form. Then, on the next request, validate the data and unserialize it. If it fails the validation test, you'll know someone has tried to modify the information.

The pc_encode( ) encoding function shown in Example 9-2 takes the data to encode in the form of an array.

Example 9-2. pc_encode( )
$secret = 'Foo25bAr52baZ';

function pc_encode($data) {
  $data = serialize($data);
  $hash = md5($GLOBALS['secret'] . $data);
  return array($data, $hash);
}

In function pc_encode( ), the data is serialized into a string, a validation hash is computed, and those variables are returned.

The pc_decode( ) function shown in Example 9-3 undoes the work of its counterpart.

Example 9-3. pc_decode( )
function pc_decode($data, $hash) {
  if (!empty($data) && !empty($hash)) {
    if (md5($GLOBALS['secret'] . $data) == $hash) {
      return unserialize($data);
    } else {
      error_log("Validation Error: Data has been modified");
      return false;
    }
  }
  return false;
}

The pc_decode( ) function recreates the hash of the secret word and compares it to the hash value from the form. If they're equal, $data is valid, so it's unserialized. If it flunks the test, the function writes a message to the error log and returns false.

These functions go together like this:

<?php
$secret = 'Foo25bAr52baZ';

// Load in and validate old data
if (! $data = pc_decode($_GET['data'], $_GET['hash'])) {
  // crack attempt
}

// Process form (new form data is in $_GET)

// Update $data
$data['username'] = $_GET['username'];
$data['stage']++;
unset($data['password']);

// Encode results
list ($data, $hash) = pc_encode($data);

// Store data and hash inside the form
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="get">
...

<input type="hidden" name="data" 
       value="<?php echo htmlentities($data); ?>">
<input type="hidden" name="hash" 
       value="<?php echo htmlentities($hash); ?>">
</form>

At the top of the script, we pass pc_decode( ) the variables from the form for decoding. Once the information is loaded into $data, form processing can proceed by checking in $_GET for new variables and in $data for old ones. Once that's complete, update $data to hold the new values and then encode it, calculating a new hash in the process. Finally, print out the new form and include $data and $hash as hidden variables.

9.4.4 See Also

Recipe 8.6 and Recipe 8.7 for information on using the session module; Recipe 9.9 for details on using htmlentities( ) to escape control characters in HTML output; Recipe 14.4 for information on verifying data with hashes; documentation on session tracking at http://www.php.net/session and in Recipe 8.5; documentation on serialize( ) at http://www.php.net/serialize and unserialize( ) at http://www.php.net/unserialize.

    Previous Section Next Section
    Index: [SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N][O][P][Q][R][S][T][U][V][W][X][Z]


         Main Menu
    Main Page
    Table of content
    Copyright
    Preface
    Chapter 1. Strings
    Chapter 2. Numbers
    Chapter 3. Dates and Times
    Chapter 4. Arrays
    Chapter 5. Variables
    Chapter 6. Functions
    Chapter 7. Classes and Objects
    Chapter 8. Web Basics
    Chapter 9. Forms
    9.1 Introduction
    Recipe 9.2 Processing Form Input
    Recipe 9.3 Validating Form Input
    Recipe 9.4 Working with Multipage Forms
    Recipe 9.5 Redisplaying Forms with Preserved Information and Error Messages
    Recipe 9.6 Guarding Against Multiple Submission of the Same Form
    Recipe 9.7 Processing Uploaded Files
    Recipe 9.8 Securing PHP's Form Processing
    Recipe 9.9 Escaping Control Characters from User Data
    Recipe 9.10 Handling Remote Variables with Periods in Their Names
    Recipe 9.11 Using Form Elements with Multiple Options
    Recipe 9.12 Creating Dropdown Menus Based on the Current Date
    Chapter 10. Database Access
    Chapter 11. Web Automation
    Chapter 12. XML
    Chapter 13. Regular Expressions
    Chapter 14. Encryption and Security
    Chapter 15. Graphics
    Chapter 16. Internationalization and Localization
    Chapter 17. Internet Services
    Chapter 18. Files
    Chapter 19. Directories
    Chapter 20. Client-Side PHP
    Chapter 21. PEAR
    Colophon
    Index


    More Books
    PHP Hacks
    Processing Xml With Java - A Guide To Sax, Dom, Jdom, Jaxp, And Trax
    The Koran (Holy Qur'an)
    Macromedia Flash 8 Bible
    Search Engine Optimization for Dummies
    YouTube Traffic
    PHP 5 for Dummies
    Harry Potter and The Chamber of Secrets
    Harry Potter and the Sorcerer's Stone
    The Pilgrim's Progress
    Wireless Hacks
    Flash Hacks. 100 Industrial-Strength Tips & Tools
    PayPal Hacks. 100 Industrial-Strength Tips and Tools
    Amazon Hacks
    Pdf Hacks
    The Da Vinci Code
    Google Hacks
    The Holy Bible
    Windows XP For Dummies
    Harry Potter and the Half-Blood Prince
    Seo Book
    Upgrading and Repairing Networks
    Macromedia Dreamweaver 8 UNLEASHED
    Windows XP Annoyances
    Windows XP Hacks
    Microsoft Windows XP Power Toolkit
    Teach Yourself MS Office In 24Hours
    iPod & iTunes Missing Manual
    PC Hacks 100 Industrial-Strength Tips and Tools
    PC Overclocking, Optimization, and Tuning - 2th Edition
    PC Hardware In A Nutshell 3rd Edition
    PC Hardware in a Nutshell, 2nd Edition
    Upgrading and Repairing PCs
    Google for Dummies
    MySQL Cookbook
    Teach Yourself Macromedia Flash 8 In 24 Hours
    PHP CookBook
    Sams Teach Yourself JavaScript in 24 Hours
    PHP5 Manual
    Free Games Paper Airplanes
    500 Juegos Gratis 500 Giochi Gratis 500 Jeux Gratuits 500 Jogos Gratis 500 Kostenlose Spiele