Form Handling | PHP Dev

PHP Form Handling

Use $_SERVER['PHP_SELF'] as a Form Action

The $_SERVER auto-global array holds various useful server- and request-specific info. The PHP_SELF element of $_SERVEVER holds the filename of the currently executing script (relative to your website's document root directory). So, supplying $_SERVER['PHP_SELF'] as the action attribute of the form element makes the FORM submit to the same page that displayed it. This lets you put the logic to handle the FORM in the same page as the logic that displays it. For many simple FORMs, this keeps things easy to manage.

Put [] at the end of the Name of a Multivalued Form Parameter

When you've got a FORM element like select multiple that can submit multiple values to the server, put [] at the end of the FORM element name so that the PHP interpreter knows to accept multiple values.

Consider the following FORM:

Dessert Picker

        <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
          <fieldset>
            <legend>Dessert Picker</legend>
            <label for="desserts">Pick some desserts:</label>
            <select name="sweet[]" id="desserts" multiple>
              <option value="puff">Sesame Seed Puff</option>
              <option value="square">Coconut Milk Gelatin Square</option>
              <option value="cake">Brown Sugar Cake</option>
              <option value="ricemeat">Sweat Rice and Meat</option>
            </select>
            <input type="submit" name="Order">
          </fieldset>
        </form>

If you pick Sesame Seed Puff and Brown Sugar Cake and submit the FORM, then $_POST['sweet'] is itself an array. $_POST['sweet'][0] is puff and $_POST['sweet'][1] is cake. That's because the name attribute of the select element is sweet[]. If the name was just sweet, then $_POST['sweet'] would be a string, holding only one of the selected values.

PHP Form Validation System: An Object-Oriented Approach

User-Friendly Forms in PHP

User Friendly Form Validation with PHP and CSS


Warning: require_once(/assets/elements/footer-dev.html) [function.require-once]: failed to open stream: No such file or directory in /nfs/c01/h06/mnt/45373/domains/dev.bowdenweb.com/html/php/form-handling.html on line 76

Fatal error: require_once() [function.require]: Failed opening required '/assets/elements/footer-dev.html' (include_path='.:/usr/local/php-5.3.29/share/pear') in /nfs/c01/h06/mnt/45373/domains/dev.bowdenweb.com/html/php/form-handling.html on line 76