How to validate input data in PHP

  • Tech Area
  • July 17, 2024



In this tutorial, We will see how to validate form input data in php using filter_input() function. In last tutorial, We learnt How to sanitize input data in php. We are using filter_input() function to validate input field like email and number.

Files used in this tutorial:

1- index.php (registration form with filter_input() function)

Create a file for registration form

Now create a new file index.php This is the main file used for registration form and validate input data.

This screenshot shows the registration form.

Validate input data in PHP

index.php

<html>  
<head>  
    <title>Registration Form</title>  
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
</head>
<style>
 .box
 {
  width:100%;
  max-width:600px;
  background-color:#f9f9f9;
  border:1px solid #ccc;
  border-radius:5px;
  padding:16px;
  margin:0 auto;
 }
 .msg
{
  color: red;
  font-weight: 700;
} 
</style>
<?php
$msg="";
if(isset($_POST['register']))
{
  $email = filter_input(INPUT_POST, "email", FILTER_VALIDATE_EMAIL);
  $phone = filter_input(INPUT_POST, "phone", FILTER_VALIDATE_INT);
  if(!empty($email))
  {
    $msg = "You have entered $email";
  }
  else if(!empty($phone))
  {
    $msg = "You have entered $phone";
  }
  else
  {
    $msg = "Error!";
  }
}
?>
<body>  
    <div class="container">  
    <div class="table-responsive">  
    <h3 align="center">Registration Form</h3>
    <div class="box">
     <form method="post">
       <div class="form-group">
       <label for="email">Enter Your Email</label>
       <input type="text" name="email" id="email" placeholder="Enter Email" class="form-control"/>
      </div>
      <div class="form-group">
       <label for="phone">Enter Your Phone No.</label>
       <input type="text" name="phone" id="phone" placeholder="Enter Phone No." class="form-control"/>
      </div>
       <div class="form-group">
       <input type="submit" id="register" name="register" value="Submit" class="btn btn-success" />
       </div>
       <p class="msg"><?php if(!empty($msg)){ echo $msg; } ?></p>
     </form>
     </div>
   </div>  
  </div>
 </body>  
</html>


Subscribe us via Email

Join 10,000+ subscriber

Subscribe on YouTube