Book HomePHP CookbookSearch this book

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.



Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.