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.

<html>
<head>
  <title>My form</title>
</head>

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

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.

<?php
  $name = $_GET['name'];
  if(empty($name)){
    echo "You must enter your name.";
  }
  else{
    echo "Hello there, $name.";
  }
?>

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