The error message is printing out when the page loads. Any ideas on this?
<?php
//Turn on sessions
session_start();
//Find what stage to use
if (($_SERVER['REQUEST_METHOD'] == 'GET') || (!isset($_POST['stage'])))
{
$stage = 1;
}
else
{
$stage = (int) $_POST['stage'];
}
// Save any submitted data
if ($stage > 1)
{
foreach ($_POST as $key => $value)
{
$_SESSION[$key] = $value;
}
}
if ($stage == 1)
{
?>
<?php
if($_SERVER['$_REQUEST_METHOD'] == 'GET')
{
//just display the form if the request is a GET
display_form(array());
}
else
{
//The request is a POST, so validate the form
$errors = validate_form();
if (count($errors))
{
//If there were errors, redisplay the form with the errors
display_form($errors);
}
}
?>
<form action='<?php echo $_SERVER['SCRIPT_NAME'] ?>' method='post'>
First Name:
<?php print_error('first_name',$errors) ?>
<input type='text' name='first_name' />
<br />
<input type='hidden' name='stage' value='<?php echo $stage + 1 ?>' />
<input type='submit' name='submit' value='Next' />
</form>
<?php
}
else if ($stage == 2)
{
?>
<form action='<?php echo $_SERVER['SCRIPT_NAME'] ?>' method='post'>
Favorite Color:
<input type='text' name='color' />
<input type='hidden' name='stage' value='<?php echo $stage +1 ?>'/>
<input type='submit' value='Done'/>
</form>
<?php
//Validation for the second stage
}
else if ($stage == 3)
{
?>
Hello <?php echo $_SESSION['first_name'] ?>.
Your favorite color is <?php echo $_SESSION['color'] ?>
<?php
}
// A helper function to make error message easier
function print_error($key, $errors)
{
if (isset($errors[$key]))
{
print "<dd class='error'>{$errors[$key]}</dd>";
}
}
function display_form($errors)
{
//Set up defaults
$defaults['first_name'] = isset($_POST['first_name'])? htmlentities($_POST['first_name']) : '';
}
function validate_form()
{
//Start out with no errors
$errors = array();
//first_name is required and must be at least 2 characters
if (! (isset($_POST['first_name']) && (strln($_POST['first_name']) > 1)))
{
$errors['first_name'] = 'Please enter a name of at least 2 letters.';
}
return $errors;
}
?>