9.2. Form Handling

As previously mentioned, a separate form handler is necessary to do something useful with the data. Form handlers are generally script files designed to interact with e-mail, databases, or some other system. For example, a Perl program might be used to query a database based on user input and then pass the results back to the user via a separate document.

A simple PHP form handler that logs form data to a file might resemble the following:

<?php

// Open LOG file
$log = fopen("formdata.log","a");

// For each value pair, output value to LOG
$firstvalue=TRUE;
foreach ($_POST as $key => $value) {
  if (!$firstvalue) { fwrite($log,", "); }

  // If value is array (multiple select list)
  //   output array to LOG (elements sep by - )
  if (is_array($value)) {
    $firstelement=TRUE;
    fwrite($log,"\"");
    foreach ($value as $element) {
      if (!$firstelement) {
        fwrite($log,"-");
        $firstelement=FALSE;
      }
      fwrite($log,$element);
    }
  } else {
    // Not array, output simple value
    fwrite($log,"\"$value\"");
    $firstvalue=FALSE;
  }
}

// Line feed and close LOG
fwrite($log,"\n");
fclose($log);

?>

Note that this form handler is very basic—it doesn't do any error checking, convert encoded values, or provide any feedback to the user. It simply takes the fields data passed to it and puts it in a comma-separated value (CSV) log file.

Common form handlers are created in Perl, Python, PHP, or other server-side programming languages.

More information on scripting languages that can be used for form handling can ...

Get Web Standards Programmer's Reference: HTML, CSS, JavaScript®, Perl, Python®, and PHP 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.