9.3. Working with Multipage Forms
Problem
You want to use a form that displays more than one page and preserve data from one page to the next.
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']); ?>">
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 ...
Get PHP Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.