PHP Forms

PHP Form Validation

Form validation is one of the major parts of web development in PHP. A PHP form is vulnerable to several threats, especially during the submission. If the forms are not submitted securely then unwanted viruses and malware can harm the PHP host server and database.

Read Also: PHP Form Handling

Form Validation in PHP

The Required field will check whether the field is filled or not in the proper way. In most cases, we will use the * symbol for the required field.

Pictorial representation

What is Validation?

Validation checks if the information submitted by the user complies with the requirements specified in the form and is correct. There are two types of validation:

  •   Client-Side validation− The client-side validation is performed on the client machine web browsers.
  •   Server-Side validationAfter submitting the data, it is sent to a server and where it undergoes another round of validation by the server machine.
Field Validation Rules
Name Required. + Must only contain letters and whitespace
E-mail Required. + Must contain a valid email address (with @ and .)
Website Optional. If present, it must contain a valid URL
Comment Optional. Multi-line input field (text area)
Gender Required. Must select one anyone but not multiple
Radio Must be selectable at least once
CheckBox Must be checkable at least once
Drop-Down menu Must be selectable at least once

An HTML form contains many input fields such as text box, checkbox, radio buttons, submit button, and checklist. The input fields need to be validated, which specifies that the user has entered information in all the required fields that are valid and correct.

General Form Validations in PHP

The details provided by the user don’t need to be always correct. PHP validates the data which is submitted by HTML form. We need to validate a few things on the server-side:

  1. Empty String
  2. Validate String
  3. Validate Numbers
  4. Validate Email
  5. Validate URL
  6. Input length

Empty String

The block of code below checks that the field is not empty. If the user skips the required field empty, it will generate an error message.

if ( empty ($_POST["name"])){

    $errMsg = "Error! You didn't enter the Name.";

    echo $errMsg;

}else{

    $name = $_POST["name"];

}

Validate String

The block of code below checks if the input field contains only alphabets and whitespace. If the name field does not get the valid input from the user, then it will generate an error message

$name = $_POST ["Name"];

if (!preg_match ("/^[a-zA-z]*$/", $name) ){

    $ErrMsg = "Only alphabets and whitespace are allowed.";

    echo $ErrMsg;

}else{

    echo $name;

}

Validate Number

The block of code below validates that the field will only contain a numeric value. If the Mobile no doesn’t receive numeric data from the user, the code will generate an error message:

$mobileno = $_POST ["Mobile_no"];

if (!preg_match ("/^[0-9]*$/", $mobileno) ){

    $ErrMsg = "Only numeric value is allowed.";

    echo $ErrMsg;

}else{

    echo $mobileno;

}

Validate Email

The valid email must contain @ &. Symbols. PHP provides various methods to validate the email address. Now we will use regular expressions to validate the email address.

The below block of code validates the email address. If the email is not valid, then the code will generate an error message:

$email = $_POST ["Email"];

$pattern = "^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$^";

if (!preg_match ($pattern, $email) ){

    $ErrMsg = "Email is not valid.";

    echo $ErrMsg;

}else{

    echo "Your valid email address is: " .$email;

}

Input Length Validation

The input length validation allows the user to provide the value between the specified range. For example, a valid mobile number must have ten digits.

$mobileno = strlen ($_POST ["Mobile"]);

$length = strlen ($mobileno);

if ( $length < 10 && $length > 10){

    $ErrMsg = "Mobile must have 10 digits.";

    echo $ErrMsg;

}else{

    echo "Your Mobile number is: " .$mobileno;

}

Validate URL

The below block of code validates the URL of the website. If the URL is not valid, it will generate an error message.

$websiteURL = $_POST["website"];

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

    $websiteErr = "URL is not valid";

    echo $websiteErr;

}else{

    echo "Website URL is: " .$websiteURL;

}

Button Click Validate

The below block of code validates that the user clicks on the submit button and sends the form data to the server using one of the following methods – GET or POST.

if (isset ($_POST['submit']){

    echo "Submit button is clicked.";

    if ($_SERVER["REQUEST_METHOD"] == "POST"){

        echo "Data is sent using POST method ";

    }

}else{

    echo "Data is not submitted";

}

Now we will apply all these validations to an HTML form to validate the fields.

Simple PHP Registration Form Validation

<!DOCTYPE html>  

<html>  

<head>  

<style>  

.error {color: #FF0001;}  

</style>  

</head>  

<body> 

<?php  

// define variables to empty values  

$nameErr = $emailErr = $mobilenoErr = $genderErr = $websiteErr = $hobbyErr = "";  

$name = $email = $mobileno = $gender = $website = $hobby = "";  

//Input fields validation  

if ($_SERVER["REQUEST_METHOD"] == "POST") {  

 //String Validation  

 if (empty($_POST["name"])){  
     $nameErr = "Name is required";  
 } else {  
     $name = input_data($_POST["name"]);  

     // check if name only contains letters and whitespace  

     if (!preg_match("/^[a-zA-Z ]*$/",$name)) { 
         $nameErr = "Only alphabets and white space are allowed";  
     }  
 }  
 //Email Validation   
 if (empty($_POST["email"])) {  
    $emailErr = "Email is required";  
 } else {
    $email = input_data($_POST["email"]);  

     // check that the e-mail address is well-formed  

     if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { 
         $emailErr = "Invalid email format";  
     } 

 }  

 //Number Validation  
 if (empty($_POST["mobileno"])) {
     $mobilenoErr = "Mobile no is required";  
 } else {
     $mobileno = input_data($_POST["mobileno"]); 
     // check if mobile no is well-formed  
     if (!preg_match ("/^[0-9]*$/", $mobileno) ) { 
         $mobilenoErr = "Only numeric value is allowed.";  
     } 

     //check mobile no length should not be less and greater than 10  

     if (strlen ($mobileno) != 10) {  

         $mobilenoErr = "Mobile no must contain 10 digits.";  

     }
 }  

      

 //URL Validation      

 if (empty($_POST["website"])){

   $website = "";  

 }else{  

  $website = input_data($_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 = "Invalid URL";

  }
  
 }

 //Empty Field Validation  

 if (empty ($_POST["gender"])){

  $genderErr = "Gender is required";  

 }else{

  $gender = input_data($_POST["gender"]);  

 }

 //Checkbox Validation  

 if (!isset($_POST['hobbies'])){  

  $hobbyErr = "You must select hobby.";  

 }else{

  $hobby = input_data($_POST["hobbies"]); 

 }  

}  

function input_data($data){

 $data = trim($data);  

 $data = stripslashes($data);  

 $data = htmlspecialchars($data);  

 return $data;

}  

?>  

<h2>Registration Form</h2>  

<span class = "error">* required field </span>  

<br><br>  

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

 Name:  

 <input type="text" name="name">  

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

 <br><br>  

 E-mail:

 <input type="text" name="email">  

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

 <br><br>  

 Mobile No:  

 <input type="text" name="mobileno">  

 <span class="error">* <?php echo $mobilenoErr; ?> </span> 

 <br><br>  

 Website:  

 <input type="text" name="website">  

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

 <br><br>  

 Gender: 

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

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

 <input type="radio" name="gender" value="other"> Other  

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

 <br><br>  

 Hobbies: 

 <input type="checkbox" name="hobbies" value="Reading"> Reading 

 <input type="checkbox" name="hobbies" value="Writing"> Writing 

 <input type="checkbox" name="hobbies" value="Playing"> Playing 

 <span class="error">* <?php echo $hobbyErr; ?> </span> 

 <br><br>

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

 <br><br>                             

</form>  

<?php  

 if(isset($_POST['submit'])) {

  if($nameErr == "" && $emailErr == "" && $mobilenoErr == "" && $genderErr == "" && $websiteErr == "" && $hobbyErr == ""){

   echo "<h3 color = #FF0001> <b>You have sucessfully registered.</b> </h3>";  

   echo "<h2>Your Input:</h2>";  

   echo "Name: " .$name;  

   echo "<br>";  

   echo "Email: " .$email;  

   echo "<br>";  

   echo "Mobile No: " .$mobileno;  

   echo "<br>";  

   echo "Website: " .$website;  

   echo "<br>";  

   echo "Gender: " .$gender;  

   echo "<br>"; 

   echo "Hobby: " .$hobby;
  } else {  

   echo "<h3> <b>You didn't filled up the form correctly.</b> </h3>";  

  }

 }  

?>  

</body>  

</html>

Output

Registration form before submission

Registration form after submission

Read More: Required Fields in PHP Form

Conclusion

Form validation is important to prevent malicious users from abusing web forms. Improper form validation can lead to multiple threats and vulnerabilities of the network. Attacks like Cross-site scripting or SQL injection become common. Therefore, having a clear understanding of how to validate a form is essential. 

We hope you have been able to understand the article. If you want to understand the other concepts of PHP programming, do refer to the PHP Tutorial and PHP MySQL sections. Happy Learning 🙂

Sahil Jani

Share
Published by
Sahil Jani

Recent Posts

5 Important Things To Know About WordPress Before You Use It

There is a reason big-name companies like CNN use WordPress. WordPress is a popular content…

3 years ago

How to Install MySQL on Your PC in 3 Easy Steps

In this tutorial, I'm going to show you how to install MySQL on your computer.…

5 years ago

Download and Install Turbo C++ for Windows 10 (Full Installation Guide)

Download Turbo C++ for windows 10 in just 7 Mb and run your first C++…

5 years ago

PHP .HTACCESS Redirects

We can redirect any webpage to any other or redirect the whole domain or website…

5 years ago

PHP Redirect Pages

There are lots of methods to redirect pages, like refresh-redirect from META tag, redirect from…

5 years ago

PHP Include & Required

Include files in PHP are used in appending various global or config files. We can…

5 years ago