In general a form is a simple HTML element containing input fields and a submit button. Forms, being a number one tool for Internet interactivity, are extremely important features in HTML, and thus in PHP as well. A simple form example is shown below.

Example of a simple HTML form and PHP

<form action="action.php" method="post">
    <p>First name: <input type="text" name="fname" /></p>
    <p>Last name: <input type="text" name="lname" /></p>
    <p>Age: <input type="text" name="age" /></p>
    
    <p><input type="submit" /></p>
</form>

In the example above, after clicking on the submit button, the form executes script found on the location defined by the attribute action ("action.php"). The variables passed to the server that will be interpreted are accesed with superglobal variables, defined with the attribute method (in this case POST). The script action.php may contain a very simple or a complex piece of code to read, sanitate, and process field values passed to it upon submission. The example below shows two simple approaches to reading and returning the form values.

Simple example of form data read in PHP via $_POST superglobal

<p>Hello <?php echo htmlspecialchars($_POST['name']; ?>.</p>

<p>Your age is <?php echo (int)&_POST['age']; ?>.</p>

NOTE: The function htmlspecialchars() is used to strip HTML tags from being interpreted as strings, or in other words "<p>Hello" will be returned as "Hello" which.

 

More about form you  can find on these links:

  1. HTML 4 Forms
  2. HTML 4 Forms- attributes
  3. HTML 5 Forms
  4. HTML 5 Forms- attributes

 

›› go to examples ››