Open In App

What are the best input sanitizing functions in PHP ?

Sanitizing data means removing any illegal character from the data. Sanitizing user input is one of the most common tasks in a web application. 
To make this task easier PHP provides native filter extension that you can use to sanitize the data such as e-mail addresses, URLs, IP addresses, etc.
The PHP Filter Extension: PHP filters are used to sanitize and validate external input. The PHP filter extension has many of the functions needed for checking user input, and is designed to do data sanitization easier and quicker. This function, when using the flag in the example, is making sure that the code removes all characters except letters, digits and the following characters !#$%&’*+-=?_`{|}~@.[] . 
Advantages of using Filters: Many web applications receive external input. External input/data can be: 
 

Sanitizing a String: The following example uses the filter_var() function to remove all HTML tags from a string.
Program 
 






<?php
 
//Use of filter_var()
$str = "<h1>GeeksforGeeks</h1>";
 
$newstr = filter_var($str,
    FILTER_SANITIZE_STRING);
     
echo $newstr;
?>

Output: 
GeeksforGeeks


 

Sanitizing an Email Address: The following example uses the filter_var() function to remove all illegal characters from the $email variable.
Program:
 






<?php
 
$email = "geeksforgeeks@gmail.co<m>";
  
// Remove all illegal characters
// from email
$nemail = filter_var($email,
        FILTER_SANITIZE_EMAIL);
         
echo $nemail;
?>

Output: 
geeksforgeeks@gmail.com


 

Sanitizing a URL: The following example uses the filter_var() function to remove all illegal characters from a URL:
Program: 
 




<?php
 
$url = "www.geeksforgeeks.or°g";
  
// Remove all illegal characters
// from a url
$nurl = filter_var($url,
        FILTER_SANITIZE_URL);
         
echo $nurl;
?>

Output: 
www.geeksforgeeks.org


 


Article Tags :