Craig Francis


PHP Form Setup

There are a number of ways to handle form submissions on websites.

One that seems to be quite popular, originally used in the good old days of the /cgi-bin/... this is where the <form> is put in a static HTML file, with its 'action' set to the URL of a server side script - which will either show a list of error messages, or a 'thank you' page.

However there are three fairly large problems:

  1. If the data contains errors, the user will need to use their 'back' button - which in the wonderful world of Internet Explorer, means the user will return to an empty form.
  2. If the data is valid, the user will be shown the 'thank you' page, where they can simply refresh the page to re-submit the data.
  3. If the user links from your 'thank you' page, but later uses their browsers 'back' button, they will be presented with a message about the page expiring.

As an alternative, for the past few years I have been roughly using the following setup:

<?php

// ------------------------
// Get submitted values

$act = (isset($_POST['act']) ? $_POST['act'] : '');
$name = (isset($_POST['name']) ? $_POST['name'] : '');

// ------------------------
// No errors by default

$htmlErrors = array();

// ------------------------
// On form submission

if ($act != '') {

// ------------------------
// Validation

if ($name == '') {
$htmlErrors['name'] = 'Your name is required';
}

// ------------------------
// If there are no errors

if (count($htmlErrors) == 0) {

// ------------------------
// Process the data

mail(...);

// ------------------------
// Send to thank you page

goto('/contact/thankYou/');

}

}

?>
<form action="./" method="post">

<?php
if (count($htmlErrors) > 0) {
echo '<ul class="error">';
foreach ($htmlErrors as $htmlError) {
echo '<li>' . $htmlError . '</li>';
}
echo '</ul>';
}
?>

<input type="text" name="name" value="<?= html($name) ?>" />
<input type="hidden" name="act" value="submit" />
<input type="submit" value="Send" />

</form>

Some notes on this technique...

Any feedback would be greatly appreciated. If you would like to use this code, please read the licence it is released under.