HomeLanguagesWhat are the best input sanitizing functions in PHP ?

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




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


Output: 

neveropen


 

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

php




<?php
 
$email = "[email protected]<m>";
  
// Remove all illegal characters
// from email
$nemail = filter_var($email,
        FILTER_SANITIZE_EMAIL);
         
echo $nemail;
?>


Output: 

[email protected]


 

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

php




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


Output: 

www.geeksforgeeks.org


 

RELATED ARTICLES

Most Popular

Dominic
32541 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6920 POSTS0 COMMENTS
Nicole Veronica
12036 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12143 POSTS0 COMMENTS
Shaida Kate Naidoo
7055 POSTS0 COMMENTS
Ted Musemwa
7292 POSTS0 COMMENTS
Thapelo Manthata
7014 POSTS0 COMMENTS
Umr Jansen
7000 POSTS0 COMMENTS