How to sanitize input data in PHP

  • Tech Area
  • July 17, 2024



In this tutorial, We will see how to use filter_input() function to sanitize form input data in php. We are using filter_input() function to sanitize input field like name, 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 sanitize input data.

This screenshot shows the registration form.

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']))
{
  $name = filter_input(INPUT_POST, "name", FILTER_SANITIZE_SPECIAL_CHARS);
  $email = filter_input(INPUT_POST, "email", FILTER_SANITIZE_EMAIL);
  $phone = filter_input(INPUT_POST, "phone", FILTER_SANITIZE_NUMBER_INT);
  if(!empty($name))
  {
    $msg = "You have entered $name";
  }
  else 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="name">Enter Your Name</label>
       <input type="text" name="name" id="name" placeholder="Enter Name" class="form-control"/>
      </div>  
       <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