PHP forms

This assumes you know how to set up a form on a Web page. This is where PHP gets interesting as handling user input is one of the two most useful things which PHP does.

As you will know from the page on HTML forms each form has an action. That describes how the form data should be handled. Setting the action to a PHP page lets that page process the data:

<form method="post" action="form1process.php">
    <p>Type your first name here: <input type="text" name="firstname" /></p>
    <p>Type your surname here: <input type="text" name="surname" /></p>
    <p>Your date of birth (dd/mm/yyyy): <input type="text" name="dob" id="dob" /></p>
<input type="submit" name="submit">
</form>
        

Paste that into the BODY of a new Web page and save it as form1.php (it could be form1.html as there is no PHP). Then create another new PHP page called form1process.php with this inside the BODY:

<?php

    $firstname=$_POST["firstname"];
    $surname=$_POST["surname"];
    $dob=$_POST["dob"];
    
    echo "Hello $firstname $surname I believe you were born $dob";

?>            
        

Save and upload both. Load form1.php in a browser and it should just show the form. Fill in the fields. Press submit.

The second page should display the data back. The way the data got there is:

  1. this HTML form sends the data using the POST method with an action of the second PHP page
  2. once POSTed the form data will be held on the server in the $_POST super global
  3. the second page gets the data from the server using $_POST and puts it into normal variables
  4. the normal variables are then used to display the data

You will probably create a lot of form processing pages in PHP as that is one of the things PHP does best. The steps are always the same. First display a form which has an action of the processing page, then get the data from $_POST and use it. Here that is done on two pages so that you understand the process but there is a better way...

Troubleshooting

Make sure the ACTION is pointing at the second page. Make sure you have refreshed the form page if you have made any changes. Use PRINT_R to show the whole contents of the $_POST superglobal.

submit to reddit Delicious Tweet