JavaScript Tutorial

PHP Forms

Forms are designed to get input from the user and send it to the server for processing. Forms are composed of Graphical User Interface such as Input Box, Radio Buttons, Checkboxes to get various types of information from the user. PHP Superglobals $_GET and $_POST are used to collect form data.

A Simple HTML Form Creation:

// form.php
<!DOCTYPE html>
<html>
	<head>
		<title>Form Handling</title>
	</head>
	<body>
		<form action="process.php" method="POST">
			<table cellpadding="10" cellspacing="5">
				<tr>
					<td>Name <asterisk style="color:red">*</asterisk></td>
					<td><input type="text" name="name" /></td>
				</tr>
				<tr>
					<td>Email<asterisk style="color:red">*</asterisk></td>
					<td><input type="text" name="email" /></td>
				</tr>
				<tr>
					<td>Gender<asterisk style="color:red">*</asterisk></td>
					<td>
						<input type="radio" name="gender" value="female" checked="checked" /> Female
						<input type="radio" name="gender" value="male" /> Male
					</td>
				</tr>
				<tr>
					<td>Reviews</td>
					<td>
						<textarea rows="3" cols="15" name="reviews"></textarea>
					</td>
				</tr>
				<tr>
					<td colspan="2" align="center">
						<input type="submit" name="submit" value="SUBMIT">
					</td>
				</tr>
			</table>
		</form>
	</body>
</html>

  • When the user fills the above form, the form data will be sent to the process.php file for further processing as mentioned in the action attribute of form tag.
  • The form data is sent using HTTP POST method.
  • In order to display the entered data, we need to create process.php file and simply print the variables using echo keyword.

Refer below code to understand how we do that.

// process.php
<html>
	<head>
	<title>User Info</title>
</head>
<body>
	<h4>Welcome <?php echo $_POST["name"]; ?></h4><br>
	<h5>Your Details</h5>
	<p>Email: <?php echo $_POST["email"]?></p>
	<p>Gender: <?php echo $_POST["gender"]?></p>	
	<p>Reviews: <?php echo $_POST["reviews"]?></p>	
</body>
</html>

Output will be simlar to below screenshot:

$_GET[] method will also produce the same result. In order to implement this method,

  • use method="get" instead of method="post" in form tag.
  • access variables using $_GET["variable_name"] in process.php file.

Form Validation

Form validation plays a very important role for the security of data from hackers. Validation on the form fields mentioned above will be:

Field Name

Validation Rules

Name

Required and must contain only alphabets and whitespace

Email

Required and a valid email address

Gender

Required

Reviews

Optional. Multiline reviews.

// Method 1 using POST
<form action="process.php" method="POST">

or 

// Method 2 using POST
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>" method="POST">

Method 1, form data will be sent to the process.php file as mentioned in the action attribute.

Method 2, $_SERVER["PHP_SELF"] is a super global variable that will return the same filename in which the current script is being executed. 

Note*:  The htmlspecialchars() function converts the special characters into html entities, thereby preventing hackers from attacking the code through html or Javascript code.

After receiving the form values, we need to validate the values properly. Some of the ways are defined as under:

  1. Check for the empty values.
  2. Pass all the values from htmlspecialchars() function so that no injected script could be executed.
  3. Use trim() function in order to remove extra spaces from text field values.
  4. Use stripslashes() function in order to remove backslashes from input values.

We will create a customized function dataCheck() to perform step 2,3 and 4 repeatedly. Validation will be performed as below:

// Form Validation
<?php	
	if(isset($_SERVER["REQUEST_METHOD"]) && $_SERVER["REQUEST_METHOD"] == "POST"){
		$errorMsg = $name = $gender = $email = $reviews = "";
    	if(isset($_POST["name"]) && $_POST["name"] != ""){   // check for empty value
$name = dataCheck($_POST["name"]);
}else{
	$errorMsg = "Please enter name";	    // error message is set
}
if(isset($_POST["email"]) && $_POST["email"] != ""){
$email = dataCheck($_POST["email"]); 
}else{
	$errorMsg = "Please enter email";
}
if(isset($_POST["gender"]) && $_POST["gender"] != ""){
      	$gender = dataCheck($_POST["gender"]);
}else{
	$errorMsg = "Gender is required";
}
if(isset($_POST["reviews"]) && $_POST["reviews"] != ""){
	$reviews = dataCheck($_POST["reviews"]);
}	
}
function dataCheck($value){
$value = stripslashes(trim($value));
$value = htmlspecialchars($value);
return $value;
}
?>

Here we have checked the required data fields for empty values and if exists, the $error is set to 1 in order to display an error message. In a similar way, any number of validation checks can be added to form fields according to the requirement. For example:  valid email Id check can be added as under:

// Validating email 

if(isset($_POST["email"]) && $_POST["email"] != ""){       //condition to check if email input box left empty or not
       $email = dataCheck($_POST["email"]);
       if (!filter_var($email,  FILTER_VALIDATE_EMAIL)){       //Validating email using FILTER_VALIDATE_EMAIL
              $errorMsg = "Email Id is not valid";
       }
}else{
       $errorMsg = "Please enter email";
}
// Validating name

if(isset($_POST["name"]) && $_POST["name"] != ""){   // check for empty value
       $name = dataCheck($_POST["name"]);
       if (!preg_match("/^[a-zA-Z-' ]*$/",$name)) {   // validate for special characters
              $errorMsg = "Please enter a valid name";
       }
}else{
       $errorMsg = "Please enter name";	    // error message is set
}

This way, the validations are added to fields to ensure the safe entry of data into the database. Here is the complete form submition and validation example:

Create a file using name userForm.php

<?php    
         if(isset($_SERVER["REQUEST_METHOD"]) && $_SERVER["REQUEST_METHOD"] == "POST"){
              $errorMsg = $name = $gender = $email = $reviews = "";
              if(isset($_POST["name"]) && $_POST["name"] != ""){   // check for empty value
   	               $name = dataCheck($_POST["name"]);
   	               if (!preg_match("/^[a-zA-Z-' ]*$/",$name)) {
   		         $errorMsg = "Please enter a valid name";
   	                }
              }else{
   	               $errorMsg = "Please fill all the required fields";    	// error message is set
              }
              if(isset($_POST["email"]) && $_POST["email"] != ""){
   	             $email = dataCheck($_POST["email"]);
   	             if (!filter_var($email,  FILTER_VALIDATE_EMAIL)) {
   		          $errorMsg = "Email Id is not valid";
   	             }
             }else{
   	               $errorMsg = "Please fill all the required fields";
             }
             if(isset($_POST["gender"]) && $_POST["gender"] != ""){
   	             $gender = dataCheck($_POST["gender"]);
             }else{
   	             $errorMsg = "Please fill all the required fields";
             }
             if(isset($_POST["reviews"]) && $_POST["reviews"] != ""){
   	            $reviews = dataCheck($_POST["reviews"]);
             }    
        }    //End main if
        function dataCheck($value){
            $value = stripslashes(trim($value));
            $value = htmlspecialchars($value);
            return $value;
       } // End dataCheck()
?>
       <!DOCTYPE html>
       <html>
	       <head>
   	               <title>Form Handling</title>
	       </head>
	       <body>
   	        <?php
   	 if(isset($_SERVER["REQUEST_METHOD"]) && $_SERVER["REQUEST_METHOD"] == "POST" && $errorMsg == ''){
   	      ?>
   	           <div id="userDetails">
   		      <h4>Welcome <?=ucfirst($_POST['name'])?></h4>
   		       <h5>Your Details Entered Are : </h5>
   			<table>
   			        <tr>
   				<td>Email ID : </td>
   				<td><?=$_POST['email']?></td>
   			        </tr>
   			        <tr>
   				<td>Gender : </td>
   				<td><?=$_POST['gender']?></td>
   			        </tr>
   			        <tr>
   				<td>Reviews : </td>
   				<td><?=$_POST['reviews']?></td>
   			        </tr>
   			</table>
   		            <h3 style="color:green">Thank u for the submission</h3>
   		       </div>
   	 <?php
   		 }else{
   	 ?>
                         <div>
                              <p style="color:red">
   			<?php
   				if(isset($errorMsg) && $errorMsg != ''){
   					echo $errorMsg;
   			            }
   			?>
   			</p>
   	                    </div>
   	                    <form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>" method="POST">
   		             <table cellpadding="10" cellspacing="4">
   			          <tr>
                                              <td>Name <asterisk style="color:red">*</asterisk></td>
                         <td><input type="text" name="name" 
                                      value="<?=isset($_POST['name'])  && $_POST['name']!= '' ? $_POST['name'] : ''?>" >
                         </td>
   			          </tr>
   			          <tr>
   				    <td>Email<asterisk style="color:red">*</asterisk></td>
   				    <td><input type="text" name="email" 
                                                          value="<?=isset($_POST['email']) && $_POST['email'] != ''? $_POST['email'] : ''?>" >
                                              </td>
   			            </tr>
   				<tr>
   				       <td>Gender<asterisk style="color:red">*</asterisk></td>
   				       <td>
   					<input type="radio" name="gender" value="female" 
                                                    <?=(isset($_POST['gender']) && $_POST['gender'] == 'female' ? 'checked="checked"' : '')?>>               
                                                        Female
   					<input type="radio" name="gender" value="male" 
                                                    <?=(isset($_POST['gender']) && $_POST['gender'] == 'male' ? 'checked="checked"' : '')?>> 
                                                        Male
   				       </td>
   			            </tr>
   				<tr>
   			                   <td>Reviews</td>
   				       <td><textarea rows="3" cols="15" name="reviews"></textarea></td>
   				</tr>
   				<tr>
   				        <td colspan="2"><input type="submit" name="submit" value="SUBMIT"></td>
   				</tr>
   			</table>
   		     </form>   	 
   	 <?php
   		 }
   	 ?>
         </body>
     </html>

Various output screens according to validations and after form submission are below:

When all the fields are not properly filled.

When all the fields are not properly filled.

Email Id is not a valid address

After successfully form submission

Get & Post Methods

 A form can be submitted using the get and the post method defined in method attribute of <form> tag. 

  • On submission both GET and POST methods create an array of keys and values, where keys are the names of the form fields and values contain the input entered by the user. URL in case of GET method will be like :
http://localhost/userForm.php?name=Sam&email=abc.xyz
  • However, GET passes the array through URL parameters and POST passes the array through HTTP POST Method.
  • Data sent through the GET method is visible to everyone. Also, only upto 2000 characters can be sent at a time. It is not preferred in case of sending confidential data to the server. On the other hand, Data sent through the POST method is invisible to everyone. Unlimited amount of information can be sent at a time. Forms are processed using POST method for the safety purpose.
Go back to Previous Course