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: 
 

  • User input from a form
  • Cookies
  • Web services data
  • Server Variables
  • Database query results

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

php

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output: 

www.geeksforgeeks.org


 




My Personal Notes arrow_drop_up

Recommended Posts:



If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : apoorv__maheshwari