9.1. Processing Form Input

Problem

You want to use the same HTML page to emit a form and then process the data entered into it. In other words, you’re trying to avoid a proliferation of pages that each handle different steps in a transaction.

Solution

Use a hidden field in the form to tell your program that it’s supposed to be processing the form. In this case, the hidden field is named stage and has a value of process:

if (isset($_POST['stage']) && ('process' == $_POST['stage'])) {
    process_form();
} else {
    print_form();
}

Discussion

During the early days of the Web, when people created forms, they made two pages: a static HTML page with the form and a script that processed the form and returned a dynamically generated response to the user. This was a little unwieldy, because form.html led to form.cgi and if you changed one page, you needed to also remember to edit the other, or your script might break.

Forms are easier to maintain when all parts live in the same file and context dictates which sections to display. Use a hidden form field named stage to track your position in the flow of the form process; it acts as a trigger for the steps that return the proper HTML to the user. Sometimes, however, it’s not possible to design your code to do this; for example, when your form is processed by a script on someone else’s server.

When writing the HTML for your form, however, don’t hardcode the path to your page directly into the action. This makes it impossible to rename or relocate your ...

Get PHP Cookbook 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.