I've seen few ways of processing forms with PHP. Whenever I am working with a form, I typically have two files: one for displaying the information (e.g. form.php) and the other for processing information (e.g. process_form.php). The latter uses sessions and simply redirects to the appropriate page depending on if the information submitted has been validated correctly or not. Below is a simple example of how I normally do things.
Form.php
<form name="form" action="process_form.php" method="POST">
<? $field = 'name'; ?>
<label for="<?= $field ?>">What is your name?</label>
<input type="text" id="<?= $field ?>" name="<?= $field ?>"
value="<?= !isset($_SESSION['form'][$field]) ? $_SESSION['form'][$field] : '' ?>" maxlength="60" />
<? if (!isset($_SESSION['errors'][$field])) { ?>
<label class="error" for="<?= $field ?>"><?= $_SESSION['errors'][$field] ?></label>
<? } ?>
<? $field = 'age'; ?>
<label for="<?= $field ?>">What is your age?</label>
<input type="text" id="<?= $field ?>" name="<?= $field ?>"
value="<?= isset($_SESSION['form'][$field]) ? $_SESSION['form'][$field] : '' ?>" maxlength="2" />
<? if (isset($_SESSION['errors'][$field])) { ?>
<label class="error" for="<?= $field ?>"><?= $_SESSION['errors'][$field] ?></label>
<? } ?>
<? $field = 'email'; ?>
<label for="<?= $field ?>">What is your email?</label>
<input type="text" id="<?= $field ?>" name="<?= $field ?>"
value="<?= isset($_SESSION['form'][$field]) ? $_SESSION['form'][$field] : '' ?>" maxlength="100" />
<? if (isset($_SESSION['errors'][$field])) { ?>
<label class="error" for="<?= $field ?>"><?= $_SESSION['errors'][$field] ?></label>
<? } ?>
<input type="submit" value="Submit Your Information" />
<input type="hidden" name="hid_submit" value="1" />
</form>
<?
if (isset($_SESSION['form'])) unset($_SESSION['form']);
if (isset($_SESSION['errors'])) unset($_SESSION['errors']);
?>
Process_form.php
$redirect_page = 'form.php';
$form = array();
$errors = array();
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$hid_submit = isset($_POST['hid_submit']) ? $_POST['hid_submit'] : NULL;
if ($hid_submit) {
$form['name'] = isset($_POST['name']) ? trim($_POST['name']) : '';
$form['age'] = isset($_POST['age']) ? trim($_POST['age']) : '';
$form['email'] = isset($_POST['email']) ? trim($_POST['email']) : '';
// validate fields
if (!valid($form['name'], 'name')) $errors['name'] = 'Please enter a valid name.';
if (!valid($form['age'], 'age')) $errors['age'] = 'Please enter a valid age.';
if (!valid($form['email'], 'email')) $errors['email'] = 'Please enter a valid email.';
if (count($errors)) {
$_SESSION['form'] = $form;
$_SESSION['errors'] = $errors;
} else {
$redirect_page = 'another_page.php';
}
}
}
redirect($redirect_page);
I find the following approach has worked well in most situations, however I am always looking for better ways to improve.