Handling form data with PHP

In this tutorial you will finally get to work with real user input through the use of forms and PHP code. This tutorial will show you how to create a simple PHP form which will ask for the user’s name and then display a simple message back to the user. This is what the form will look like:

Form with text box user input .
Form with text box user input .

The PHP code also includes some basic data validation that checks that the user has entered some value and asks them to enter their name if they haven’t.

Watch the video below and then scroll down to see the sample code.

Sample code

There are two files required – an HTML or PHP file which contains the form (eg. form.php), and a PHP file which handles the form data (eg. form_handler.php).

Step 1 – Create a form.php file and add the following code.

  <title>My form</title>

  <h3>Enter your name below:</h3>
  <form action="action_handler.php" method="GET">
    <p>Name: <input type="text" name="name"> <input type="submit"></p>

Step 2 – Create an action_handler.php file and add the following code. The empty function is used to check if a text box has been left empty by the user (if they haven’t entered a value in the text box). Make sure both files are in the same folder/directory.

  $name = $_GET['name'];
    echo "You must enter your name.";
    echo "Hello there, $name.";

That’s it. Now open the form.php file in your browser and try it out!