The Talent500 Blog
Data collection with PHP - Creating forms, Setting up and Validation 1

Data collection with PHP – Creating forms, Setting up and Validation

What is Form?

You always interact with a form whenever you login into your mailbox or any website.

These forms are used to get input from the user and submit it to the web server for processing.

The diagram below illustrates the process of form handling.

A form is an HTML that consists of graphical user interface items such as input boxes, check boxes, radio buttons, etc.

Create a form

Using HTML tags to create a form. A minimum list of things needed to create a form is mentioned below.

  •   <form>…</form> are Opening and closing form tags
  •   POST or GET – Form submission type
  •   Submission URL to process the submitted data
  •   Input fields like input boxes, text areas, buttons, checkboxes, etc.

Create a simple registration form with the below-given code.

<html>

<head>

     <title>Registration Form</title>

     <meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>

</head>

<body>

<h2>Registration Form</h2>

<form action=”registration_form.php” method=”POST”> First name:

     <input type=”text” name=”firstname”> <br> Last name:

     <input type=”text” name=”lastname”> 

     <input type=”hidden” name=”form_submitted” value=”1″ /> 

     <input type=”submit” value=”Submit”>

</form>

</body>

</html>

The following forms are displayed after viewing the above code in a web browser.

Data collection with PHP - Creating forms, Setting up and Validation 2

 GET and POST Methods in PHP

There are two methods through which a browser can send information to the Server. Methods are given below.

  1. GET method
  2. POST method

These methods are the HTTP request methods that are used to send form data to the server inside the <form>tag.

This protocol enables communication between the client and the server where a browser can be the client, and an application running on a computer system that hosts your website can be the server.

GET METHOD

The GET method is required to submit the HTML form data. The data is collected by the predefined $_GET variable for processing.

All variable names and their values will be displayed in the URL since the data supplied from an HTML form using the GET method is visible to everyone in the browser’s address bar. Therefore, the get method is not secure to send sensitive information.

For Example

localhost/gettest.php?username=Harry&bloodgroup=AB+  

Note: A limited amount of information can be sent using the GET method.

Example

The below code displays an HTML form containing two input fields and a submit button. In this HTML form, we used the method = “get” to submit the form data.

<html>  

<body>  

       <form action = “gettest.php” method = “GET”>  

        Username: <input type = “text” name = “username” /> <br>  

              Blood Group: <input type = “text” name = “bloodgroup” /> <br>  

            <input type = “submit” />

             </form>  

         </body>  

</html>  

Data collection with PHP - Creating forms, Setting up and Validation 3

Create a gettest.php file, It will accept the data sent by HTML form.

<html>  

   <body>       

      Welcome <?php echo $_GET[“username”]; ?> </br>  

      Your blood group is: <?php echo $_GET[“bloodgroup”]; ?>    

   </body>  

</html>  

Once the user select submit button after filling up the form, the URL sent to the server will look something like the below:

localhost/gettest.php?username=Harry&bloodgroup=AB-

The output will look as below:

Welcome Harry

Your blood group is: AB-

POST METHOD

An HTML form data is submitted using the POST method, just like with the GET method. However, instead of using $_GET to collect the data supplied by this method, the predefined superglobal variable $_POST is used.

It does not have a restriction on the amount of data that can be sent, in comparison to the GET technique. Nobody can see the data submitted from an HTML form using the POST technique.

For Example

localhost/posttest.php  

Since the sending data via the POST method is not visible to the user, it should be observed that it is more secure than the “get” method.

With a simple example, Let’s look at the working of the POST method:

Example

The below-given code displays an HTML form that contains two input fields and a submit button. We will use the post method to submit the form data.

file: test2.html

<html>  

   <body>       

      <form action = “posttest.php” method = “post”>  

         Username: <input type = “text” name = “username” /> <br>  

         Blood Group: <input type = “text” name = “bloodgroup” /> <br>  

         <input type = “submit” />  

      </form>  

   </body>  

</html>  

Data collection with PHP - Creating forms, Setting up and Validation 4

accept the data sent by HTML form create a posttest.php file.

file: posttest.php

<html>  

   <body>      

      Welcome <?php echo $_POST[“username”]; ?> </br>  

      Your blood group is: <?php echo $_POST[“bloodgroup”]; ?>    

   </body>  

</html>  

The URL sent to the server could look as below once the user clicks on Submit button after filling out the form:

localhost/posttest.php

The output will look as below:

Welcome Harry

Your blood group is: O+

Types of Validation

The table of the various field types included in the registration form, their requirements, and the field type, i.e., Mandatory or Optional, are shown below.

Field Requirement Field Type
Full Name Only letters and spaces Mandatory
Email Valid email address with “@” Mandatory
Website Valid Web Address with “.com” Optional
Gender Must select one Mandatory
Comment No requirements Optional

Every field in the table above that is marked as mandatory is a required field. As a result, you cannot submit the form without completing out the field.

While the remark area is a text field and has no requirements, the gender field on the registration page will be shown as a select option, thus the requirement is set as “Must select one”.

Writing the Code for PHP form Validation

The code that follows will generate a form containing the above fields and validate the form.

Several significant variables in the code include:

PHP uses the superglobal variable $_POST to store data that is provided through a form. Variables can also be passed through it.

The super global variable $_SERVER [“REQUEST METHOD”] additionally is used to access the page with return request method.

<!DOCTYPE HTML>  

<html>

<head>

    <style>

        .error {color: #FF0000;}

    </style>

</head>

<body>  

    <?php

        $nameErr = $emailErr = $genderErr = $websiteErr = “”;

        $name = $email = $gender = $comment = $website = “”;

        if ($_SERVER[“REQUEST_METHOD”] == “POST”) {

        if (empty($_POST[“name”])) {

            $nameErr = “Please enter a valid name”;

        } else {

            $name = test_input($_POST[“name”]);

            // check if name only contains letters and whitespace

            if (!preg_match(“/^[a-zA-Z-‘ ]*$/”,$name)) {

            $nameErr = “Only letters and white space allowed”;

            }

        }

        if (empty($_POST[“email”])) {

            $emailErr = “valid Email address”;

        } else {

            $email = test_input($_POST[“email”]);

            // check if email address is well-formed

            if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {

            $emailErr = “The email address is incorrect”;

            }

        }  

        if (empty($_POST[“website”])) {

            $website = “”;

        } else {

            $website = test_input($_POST[“website”]);

            // check if URL address syntax is valid

            if (!preg_match(“/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i”,$website)) {

            $websiteErr = “Enter a valid Website URL”;

            }    

        }

        if (empty($_POST[“comment”])) {

            $comment = “”;

        } else {

            $comment = test_input($_POST[“comment”]);

        }        

        if (empty($_POST[“gender”])) {

            $genderErr = “Please select a gender”;

        } else {

            $gender = test_input($_POST[“gender”]);

        }

        }

        function test_input($data) {

        $data = trim($data);

        $data = stripslashes($data);

        $data = htmlspecialchars($data);

        return $data;

        }

    ?>

    <h2>PHP Form Validation Example</h2>

    <p><span class=”error”>* required field</span></p>

    <form method=”post” action=”<?php echo htmlspecialchars($_SERVER[“PHP_SELF”]);?>”>  

        FullName: <input type=”text” name=”name”>

        <span class=”error”>* <?php echo $nameErr;?></span>

        <br><br>

        E-mail address: <input type=”text” name=”email”>

        <span class=”error”>* <?php echo $emailErr;?></span>

        <br><br>

        Website: <input type=”text” name=”website”>

        <span class=”error”><?php echo $websiteErr;?></span>

        <br><br>

        Comment: <textarea name=”comment” rows=”2″ cols=”10″></textarea>

        <br><br>

        Gender:

        <input type=”radio” name=”gender” value=”female”>Female

        <input type=”radio” name=”gender” value=”male”>Male

            <span class=”error”>* <?php echo $genderErr;?></span>

        <br><br>

        <input type=”submit” name=”submit” value=”Submit”>  

    </form>

    <?php

        echo “<h2> Final Output:</h2>”;

        echo $name;

        echo “<br>”;

        echo $email;

        echo “<br>”;

        echo $website;

        echo “<br>”;

        echo $comment;

        echo “<br>”;

        echo $gender;

    ?>

</body>

</html>

The first step is to give incorrect details and see the output.

Data collection with PHP - Creating forms, Setting up and Validation 5

If the correct details are entered. No error will be displayed.

Data collection with PHP - Creating forms, Setting up and Validation 6

Form Validation is an essential step before the data input in the form is transmitted to the database, This is done to avoid making unnecessary mistakes. In PHP form validation, the script verifies the data in the appropriate fields in accordance with the developer’s guidelines and produces an error if it does not.

 

0
Subhojit Hazra

Subhojit Hazra

He is a tech enthusiast and a passionate marketer with an eye for detail. He loves to uncomplicate things and debate on business problems. A quiet guy who likes peaceful evenings and iced coffees.

Add comment