How to Perform PHP Validation - dummies

By Steve Suehring, Janet Valade

Your overall goal is to make sure that any input received from the user, whether from a web form, a web service, or elsewhere, is checked and sanitized through PHP validation.

In order to pass errors back to a form, you need to use sessions. Additionally, you need to carve out a space to provide the error feedback from PHP within that form page. This means making some slight changes to a basic form.php file. That seems like a logical place to start with an exercise.

  1. Open form.php in your editor.

  2. Within form.php, add the following code to the top, above the <doctype> declaration:

    <?php session_start(); ?>
  3. Change the <div id=”errorDiv”></div> line to look like this code:

    <div id="errorDiv">
        if (isset($_SESSION['error']) && isset($_SESSION['formAttempt'])) {
            print "Errors encountered<br />n";
            foreach ($_SESSION['error'] as $error) {
                print $error . "<br />n";
            } //end foreach
        } //end if
  4. In order to test the PHP validation, you need to skip the JavaScript validation. Therefore, comment out the JavaScript validation file, form.js, so that it doesn’t load.

    The line should look like this when you’re done:

    <!-- <script type="text/javascript" src="form.js"></script> →
  5. Save form.php.

  6. Load the page in your browser at http://localhost/form.php.

The form should submit without error because the JavaScript validation has been temporarily removed.

The PHP you added to form.php starts the session and then looks to see if the session variables named error and formAttempt are set. If those are set, then you know that there are errors and that the errors are the result of a form attempt. The formAttempt session variable is then unset.

This helps for situations where users use the Back button in their browser. The formAttempt session variable will again be set next time they submit the form (as you see later).

If errors are encountered, output is created to that effect and each error message is printed to the screen. (You test it shortly.)

One other prerequisite item is to set up a success page. Follow these steps:

  1. Create a new empty text file in your editor.

  2. Place the following HTML in that file:

    <!doctype html>
    <title>A form - Success</title>
        Thank you for registering
  3. Save the file as success.php in your document root.