Forum Moderators: coopster

Message Too Old, No Replies

How to validate a php session() multi page form?

         

tora0515

4:53 pm on Feb 1, 2011 (gmt 0)

10+ Year Member



I would like to make sure that there are no empty fields. I would like to add

if (! strlen($_POST['first_name']))
{
print 'Please enter your first name.';
}


but I am not sure where to add it. any help would be appreciated.

Thanks.

<?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)
{
?>
<form action='<?php echo $_SERVER['SCRIPT_NAME'] ?>' method='post'>'

First Name:
<input type='text' name='first_name' />

<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
}
else if ($stage == 3)
{
?>
Hello <?php echo $_SESSION['first_name'] ?>
Your favorite color is <?php echo $_SESSION['color'] ?>
<?php

}
?>

eelixduppy

7:31 pm on Feb 1, 2011 (gmt 0)



Well if it is in the first "stage" that you have to input the first name, then you probably want to put that code within the second stage before you print out the second part of the form. That way you can force them to retype it if that's what you want to do.

You can also use, in addition to the PHP validation, JavaScript validation so that the user can get notified that they have submitted the form incomplete before it actually gets submitted to the server for the "real" verification.

And Welcome to WebmasterWorld! :)

tora0515

2:41 am on Feb 2, 2011 (gmt 0)

10+ Year Member



Thank you for the quick reply. That did it.