- Instant help with your Php coding problems

PHP form tutorial

If you have ever made any  HTML page or started dynamic web programming then you probably have already met with forms. Forms are special components that allow your site visitors to supply various information on the HTML page.

For example, almost every company website has a contact form where the visitor can send a message to the site owner. On such a contact form usually, there are more fields: one for the visitor name, one for the email address, and one for the main message itself. The HTML code of a basic contact form looks something similar:

<form action="form.php" method="POST">
  <table>
    <tr>
      <td>Name:</td>
      <td><input type="text" name="name"></td>
    </tr>
    <tr>
      <td>Email:</td>
      <td><input type="text" name="email"></td>
    </tr>
    <tr>
      <td>Message:</td>
      <td><textarea name="mesg"></textarea></td>
    </tr>
    <tr>
      <td><input type="submit" name="SubmitForm" value="Send"></td>
    </tr>
<form> 

Explanation:

The form tag: 

The most important part of this code is in line 1. where the form begins. No small wonder we start a form with the <form> tag. As the form is a container so you can find the closing tag in line 18. The <form> tag has more parameters but the most important is the action and the method

What do these parameters do?

Action: The action parameter tells the browser what script/site must be called when the visitor pressed the submit button. In our case, the browser will load the form.php file which will process the submitted information. See details later.

Method: The method parameters tell the browser in which form to send the user-submitted data to the web-server. The parameter value is either POST or GET . However, nowadays POST is more often used as it is more secure.

The<form> tag has many more parameters but now they are not important. The most form uses only these 2 parameters. 

 

The input fields:

Inside the form, we have a table just to display it in a usable format. Each table row has 2 cells. In the first cell, you can find a label to the input field and in the second cell, there is the <input> tag itself. In this example, we have 2 text fields in line 5 and line 9. These fields are for the user name and email address. As you can see both fields are <input> tags with the type parameter set to text.

However, the 3rd input field (Line 13) is a bit different. It is a textarea that is a special field and the usage is a bit different. This type of field was designed to make it available to write text in more lines.

One more important point is the name parameter for all the 3 input fields. This parameter helps identify the field value later during the form processing. It is important to give a unique name for each field. If you don't follow this rule then you will not get any error message but during the form processing, there will be some interesting surprise as you can not precisely identify inputs. See details later. 

 

The submit button:

The last important element is the submit button itself in line 16. It is again an <input> tag as the text fields in line 5,9 however its type is different. This is an <input> tag with the type submit. This field is displayed as a button in your browser and you can "only" click on it. And this click triggers the browser to submit the form to the server and call the script defined in the action parameter.

The value parameter is not mandatory. It is a text which will be on the button, but without this, a default value will be used.

However, the name parameter again has an important rule as later you will check it during the form processing. See details in the next step. 

PHP form processing

Now we have an HTML page with a form but if we press the submit button then we will get a Not Found message if the form.php file doesn't exist yet.  

First, you should save the HTML site shown in the previous step as form.php. Yes, it is correct, we will create a compact PHP page that will display the HTML form and process it as well. But how it is possible? It is not so complicated. We will create a code that will display the HTML form if the user visits it. If the form is submitted then the code will recognize it and instead of displaying the form we will process the submitted data.

If a form was submitted and the script defined in the action parameter of the form tag is called then a so-called superglobal array will be populated with the user-entered information. In our example we have 4 inputs: 2 input text fields, 1 textarea, and 1 input submit button. Each of them has its own name. As we defined to send form data as POST (See the method form parameter) so to $_POST array will contain 4 elements. Something like that:

$_POST['name'] : "John"
$_POST['email'] : "john@john.com"
$_POST['mesg'] : "Hello, my nam is John!"
$_POST['submitForm'] : "Send"

What does it mean? It means that we can check this array. If it is filled then the user has submitted the form and if it is empty then no submission was done so we need to display the form.

However, it can happen that the visitor submitted an empty form by just clicking on the Send button. In this case, only one of the above-mentioned array element exists and it is the submitForm. In case of submitting an HTML form, the submit button value always be present in the $_POST array. Now we can create a simple conditional statement to decide what to do. If the $_POST['submitForm'] doesn't exist then we display the form else print out a message that the form was submitted. The code to do this looks like this:

<?php
 if (!isset($_POST['submitForm'])) {
?>     
<form action="form.php" method="POST">
  <table>
    <tr>
      <td>Name:</td>
      <td><input type="text" name="name"></td>
    </tr>
    <tr>
      <td>Email:</td>
      <td><input type="text" name="email"></td>
    </tr>
    <tr>
      <td>Message:</td>
      <td><textarea name="mesg"></textarea></td>
    </tr>
    <tr>
      <td><input type="submit" name="SubmitForm" value="Send"></td>
    </tr>
<form>   
<?php
 } else {
     echo "Form submitted!";   
}
?> 

Ok, it's nice but what to do now. The visitor can submit an empty form? Yes, so now we need to extend our code with some input data validation.

PHP form validation concept

To make a usable form we need to make some input validation to avoid meaningless data input. To do this there are more ways. We can check user inputs on the client-side with JavaScript and we can do it on the server side via PHP. Of course, the best solution would be to use both methods. In this article, I will focus only on PHP form validation.

First of all, you have to decide which fields are mandatory and which are not. Afterward, you need to define what kind of input is acceptable for a specific field. For example, if you want to know the age of the visitor then the only numbers is acceptable and not a text or date. To make your form user-friendly it is a good idea to mark mandatory fields on the HTML form and if any error occurred then you should display an error message.

As the first step let's copy relevant variables into a local representation with a code like this:

$name  = isset($_POST['name'])  ? trim($_POST['name'])  : '';
$email = isset($_POST['email']) ? trim($_POST['email']) : '';
$mesg  = isset($_POST['mesg'])  ? trim($_POST['mesg'])  : '';

This code checks if the actual field was filled or not. Besides this, the code removes spaces from the beginning and end of a string. It is to avoid inputs with only spaces and helps to check the content later. If the variable was not set then we initialize the local variable with an empty string.

Now as we have the user inputs in a pure state we can make some validation on it. 

In this example, we check if the name is not empty and at least 3 characters long as there is no name with only 1 or 2 characters. (Depends on countries) . Similar to this we check the message itself but in this case, we accept only at least 9 character long texts. At least we check the email validity with regular expression. In case of any error, we set a variable for that field. In the end, our check code looks like this:

if (!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)) $errorEmail = true;
if (strlen($name)<3)  $errorName = true;
if (strlen($mesg)<10) $errorMesg = true;

In case of any error we need to display the HTML form to the visitor again but in this case, we should display the error message to help the visitor to correct it. So the use case is the following:

  1. Display the form
  2. Process user input
  3. In case of error display the form again with an error message
  4. If there is no error then go on.

To make the code more simple it makes sense to create a function that displays the HTM form and error messages if needed. The function definition should look like something similar:

showForm($errorName=false,$errorEmail=false,$errorMesg=false)

So if the function is called without any parameter a normal HTML form will be displayed, but if any error variable is set then the corresponding error message will be displayed as well. The improved form processing code looks like this: 

<?php
// Function to display form
function showForm($errorName=false,$errorEmail=false,$errorMesg=false){
   if ($errorName)  $errorTextName  = "Please enter your name!";
   if ($errorEmail) $errorTextEmail = "Please enter a valid email address!";
   if ($errorMesg)  $errorTextMesg  = "Please leave a longer message!";
 
   echo '<form action="form.php" method="POST"><table>';
 
   // Display name field an error if needed
   echo '<tr><td>Name:</td><td><input type="text" name="name"></td></tr>';
   if ($errorName) echo "<tr><td colspan='2'>$errorTextName</td></tr>";
 
   // Display email field an error if needed
   echo '<tr><td>Email:</td><td><input type="text" name="email"></td></tr>';
   if ($errorEmail) echo "<tr><td colspan='2'>$errorTextEmail</td></tr>";
 
   // Display message field an error if needed
   echo '<tr><td>Message:</td><td><textarea name="mesg"></textarea></td></tr>';
   if ($errorMesg) echo "<tr><td colspan='2'>$errorTextMesg</td></tr>";
 
 
   echo '<tr><td><input type="submit" name="SubmitForm" value="Send"></td></tr>';
   echo '<form>';
}
 
 
if (!isset($_POST['SubmitForm'])) {
   showForm();
} else {
   //Init error variables
   $errorName  = false;
   $errorEmail = false;
   $errorMesg  = false;
 
   $name  = isset($_POST['name'])  ? trim($_POST['name'])  : '';
   $email = isset($_POST['email']) ? trim($_POST['email']) : '';
   $mesg  = isset($_POST['mesg'])  ? trim($_POST['mesg'])  : '';
 
   if (!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)) $errorEmail = true;
   if (strlen($name)<3)  $errorName = true;
   if (strlen($mesg)<10) $errorMesg = true;
 
   // Display the form again as there was an error
   if ($errorName || $errorEmail || $errorMesg) {
      showForm($errorName,$errorEmail,$errorMesg);
   } else {
      echo 'Submission was success!';
   }
 
}
?> 

Of course later you can improve the look of the form and the validation itself to be more robust but for demonstration, it is enough I think.

 

Share "PHP form tutorial" with your friends