Book HomePHP CookbookSearch this book

9.2. Processing Form Input

9.2.1. 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.

9.2.2. 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();
}

9.2.3. 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 page without also editing it. Instead, PHP supplies a helpful variable:

$_SERVER['PHP_SELF'] 

This variable is an alias to the URL of the current page. So, set the value of the action attribute to that value, and your form always resubmits, even if you've moved the file to a new place on the server.

So, the example in the introduction of this chapter is now:

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

function print_form() {
    echo <<<END
        <form action="$_SERVER[PHP_SELF]" method="post">
        What is your first name?
        <input type="text" name="first_name">
        <input type="hidden" name="stage" value="process">
        <input type="submit" value="Say Hello">
        </form>
END;
}

function process_form() {
    echo 'Hello ' . $_POST['first_name'] . '!';
}

If your form has more than one step, just set stage to a new value for each step.

9.2.4. See Also

Recipe 9.4 for handling multipage forms.



Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.