Today we will learn about a new and simple topic called filters in this PHP Filters tutorial.
- What is FILTER?
- English meaning of filter is removing unwanted things and taking only what is required.
- In PHP we use filter to validate (check the valid format) and sanitize (remove unwanted data) the input data received from an external source.
- The external source can be a user input, output of a query evaluation, web service data, server variables, cookies, etc.
- Till now we used different methods and manual conditions to check, if the user has entered the data or not or if the entered data is valid or not. This requires a lot of code.
- But PHP has provided us with built in methods to decide the validity of data and filter some unwanted things with the help of different filters.
- We know that every website gets data from external sources. To make sure that we get correct input data validation is the most important task that is to be performed.
- This validation process with PHP filters becomes very easy and quick.
- Details of Validating and Sanitizing:
- Validating Filter:
- This is also called as logical Filter.
- It is used to validate user input i.e. to check if the given input is in correct format.
- It strictly follows the format rules (I mean the valid format is checked for eg. Email, url, etc.).
- It returns expected type on success and false on failure.
- Sanitizing Filter:
- It is used to allow or disallow specified characters in a string.
- It does not follow strict format types.
- It always returns a string.
- Functions used to filter data are :
- filter_var(): it filters a single variable with a specified filter.
- filter_var_array(): it filters number of variables with same or different filters.
- filter_input(): it gets one input variable and filters it.
- filter_input_array(): it gets number of input variables and filters them with same or different filters.
- There is a function called filter_list() which lists all the filters that can be used to filter the input data of different types.
- Just create a new folder named filters in the htdocs folder in xampp folder. Now open a new notepad++ document and save it as index.php in the newly created filters folder.
- Write the following code in index.php:
<html> <head> <title>FILTERS</title> </head> <body> <table> <tr> <td>Filter Name</td> <td>Filter ID</td> </tr> <?php foreach(filter_list() as $key =>$value) { echo '<tr><td>'.$value.'</td><td>'.filter_id($value).'</td></tr>'."\n"; } ?> </table> </body> </html>
Filter Name | Filter ID |
Int | 257 |
Boolean | 258 |
Float | 259 |
validate_regexp | 272 |
validate_url | 273 |
validate_email | 274 |
validate_ip | 275 |
String | 513 |
Stripped | 513 |
Encoded | 514 |
special_chars | 515 |
full_special_chars | 522 |
unsafe_raw | 516 |
517 | |
url | 518 |
number_int | 519 |
number_float | 520 |
magic_quotes | 521 |
Callback | 1024 |
<html> <head> <title>FILTERS</title> <style> h1{ margin-left:70px; } label{ display:inline-block; width:170px; } .shift{ margin-top:10px; margin-left:120px; font-weight:bold; } </style> </head> <body> <h1>Student Info</h1> <?php if($errors) { echo $errors; } ?> <form name="data" method="post" action="<?php echo $_SERVER['PHP_SELF'];?>"> <label for="name">Name:</label> <input type="text" name="name" value="<?php if(isset($_POST['name'])) echo $_POST['name'];?>"/><br> <label for="school">School Name:</label> <input type="text" name="school" value="<?php if(isset($_POST['school'])) echo $_POST['school'];?>"/><br> <label for="age">Age:</label> <input type="text" name="age" value="<?php if(isset($_POST['age'])) echo $_POST['age'];?>"/><br> <label for="per">Percentage:</label> <input type="text" name="per" value="<?php if(isset($_POST['per'])) echo $_POST['per'];?>"/><br> <label for="email">Email-ID:</label> <input type="text" name="email" value="<?php if(isset($_POST['email'])) echo $_POST['email'];?>"/><br> <label for="url">School website URL:</label> <input type="text" name="url" value="<?php if(isset($_POST['url'])) echo $_POST['url'];?>"/><br> <input class="shift" type="submit" name="submit" value="SUBMIT"/> </form></body> </html>
<?php $errors=""; if(isset($_POST["submit"])) { $name=filter_input(INPUT_POST,$_POST['name'],FILTER_SANITIZE_STRING); if($_POST['name']=="") { $errors.="Please enter your name.<br>"; } $school=filter_input(INPUT_POST,$_POST["school"],FILTER_SANITIZE_STRIPPED); if($_POST['school']=="") { $errors.="Please enter your school name.<br>"; } $age=filter_input(INPUT_POST,$_POST["age"],FILTER_VALIDATE_INT); if($_POST['age']=="") { $errors.="Please enter your age.<br>"; } elseif($agee===false) { $errors.="Please enter a valid integer number for age.<br>"; } $per=filter_input(INPUT_POST,$_POST["per"],FILTER_VALIDATE_FLOAT); if($_POST['per']=="") { $errors.="Please enter your percentage.<br>"; } elseif($per===false) { $errors.="Please enter percentage upto 2 decimals.<br>"; } $email=filter_input(INPUT_POST,$_POST["email"],FILTER_SANITIZE_EMAIL); $emaill=filter_input($email,FILTER_VALIDATE_EMAIL); if($_POST['email']=="") { $errors.="Please enter your email-id.<br>"; } elseif($emaill===false) { $errors.="Please enter your email-id in a proper format.<br>"; } $url=filter_input(INPUT_POST,$_POST["url"],FILTER_SANITIZE_URL); $urll=filter_input($url,FILTER_VALIDATE_URL); if($_POST['url']=="") { $errors.="Please enter your school website URL.<br>"; } elseif($urll===false) { $errors.="Please enter a valid URL.<br>"; } if($errors=="") { header("Location:welcome.php?name=".$_POST['name']); } } ?>
- First is the method by which the data will be accepted and transferred to another page say INPUT_POST for post method and INPUT_GET for get method.
- Next is the value entered by user.
- Next is the filter applied for that particular input.
header("Location:welcome.php?name=".$_POST['name']);
- Options and flags are the additional options to add additional filters to the specified filters.
- Different filters have different options and flags.
- Options and flags are specified in an array.
- We can provide additional validation to an input value entered by the user by giving a minimum and maximum range for an integer number, sanitizing special characters from a string etc.
- Let us see different options and flags for different types of values one by one:
- Validating Integer values:
- Setting a range for integer input:
- See the following code:
- Here, we have the integer number in a variable $no. The minimum range limit is 10 and maximum range limit is 100 which is stored in variables $min and $max.
- Here we have used filter_var() function because we are filtering a value stored in a variable. It has parameters as the variables to be filtered, the filter used to validate/sanitize the variable, options/flags.
- In this above statement
filter_var($no,FILTER_VALIDATE_INT,array("options"=>array("min_range"=>$min,"max_range"=>$max)));
we have validated the number to be an integer using FILTER_VALIDATED_INT. And the options min_range and max_range validation is added to it in an array. These options allow only those numbers which are within the given minimum and maximum range values.
- If the number fails to fit in the conditions given in filter_var() function, the filter_var() function returns false and nothing will be displayed and if it satisfies the conditions the number will be displayed.
- If you want to give only minimum range value and if you want no limit for maximum range value, then you can give only min_range in the options array and vice –a versa.
<?php $no=67; $min=10; $max=100; echo filter_var($no,FILTER_VALIDATE_INT,array("options"=>array("min_range"=>$min,"max_range"=>$max))); /* OUTPUT 67 */ ?>
- Write the following code:
<?php $octal=0XFF; if(filter_var($octal,FILTER_VALIDATE_INT,array("flags"=>FILTER_FLAG_ALLOW_OCTAL))==true) { echo "The given number is octal."; } else { echo "The given number is not an octal number."; } /* OUTPUT The given number is octal. */ ?>
if(filter_var($octal,FILTER_VALIDATE_INT,array("flags"=>FILTER_FLAG_ALLOW_OCTAL))==true)
- Using options for regular expression :
- See the code below:
<?php $name="Ashok Patil"; $pattern="/^[a-z]*/"; if(filter_var($name,FILTER_VALIDATE_REGEXP,array("options"=>array("regexp"=>$pattern)))==true) { echo $name; } else { echo $name."is not in proper format."; } /* OUTPUT Ashok Patil */ ?>
If it returns true then the value in $name variable is displayed otherwise the statement echo $name.”is not in proper format.”; will be executed.
- We can validate a URL with FILTER_VALIDATE_URL filter as shown in the form validation code.
- But a URL can be in different forms and all these forms cannot be validated using the same format of URL used by FILTER_VALIDATE_URL.
- To validate all the forms of URL 4 flags have been provided as shown below:
- FILTER_FLAG_SCHEME_REQUIRED,
- FILTER_FLAG_HOST_REQUIRED,
- FILTER_FLAG_PATH_REQUIRED,
- FILTER_FLAG_QUERY_REQUIRED
- See the code given below:
<?php $url="www.school.com"; if(filter_var($url,FILTER_VALIDATE_URL,FILTER_FLAG_SCHEME_REQUIRED)==true) { echo "The $url is valid."; } else { echo "The $url is not valid."; } /* OUTPUT The www.school.com is not valid. */ ?>
- We know sanitizing means removing unwanted data. To sanitize a string we use FILTER_SANITIZE_STRING or FILTER_SANITIZE_STRIPPED filters.
- Along with it we use flags such as
- FILTER_FLAG_NO_ENCODE_QUOTES,
- FILTER_FLAG_STRIP_LOW,
- FILTER_FLAG_STRIP_HIGH,
- FILTER_FLAG_ENCODE_LOW,
- FILTER_FLAG_ENCODE_HIGH,
- FILTER_FLAG_ENCODE_AMP.
- When we use quotes in the string, sometimes these quotes are converted to their html equivalent codes, in such situation we can use the flag FILTER_FLAG_NO_ENCODE_QUOTES and keep them from converting to html codes.
- See the following code:
<?php $str="<script>\"The Taj Mahal\"</script>"; echo filter_var($str,FILTER_SANITIZE_STRING,FILTER_FLAG_NO_ENCODE_QUOTES); /* OUTPUT "The Taj Mahal" */ ?>
&
- We use the filter FILTER_SANITIZE_ENCODED to sanitize the filter.
- Along with that we can use the flags
- FILTER_FLAG_STRIP_LOW,
- FILTER_FLAG_STRIP_HIGH,
- FILTER_FLAG_ENCODE_LOW,
- FILTER_FLAG_ENCODE_HIGH
- These are used same as for the string above.
- We can sanitize special characters using FILTER_SANITIZE_SPECIAL_CHARS filter.
- Let us see the code below:
<?php $string="we^&*{?>:(*@$"; echo filter_var($string,FILTER_SANITIZE_SPECIAL_CHARS); ?>
- FILTER_FLAG_STRIP_LOW,
- FILTER_FLAG_STRIP_HIGH,
- FILTER_FLAG_ENCODE_HIGH
- We use filter FILTER_SANITIZE_URL to sanitize a URL.
- To sanitize an integer a filter FILTER_SANITIZE_NUMBER_INT is used.
- It allows numbers + and – signs.
- See the code below:
<?php $int="12.345;+6789"; echo filter_var($int,FILTER_SANITIZE_NUMBER_INT); /* OUTPUT 12345+6789 */ ?>
- The filter FILTER_SANITIZE_NUMBER_FLOAT is used to sanitize a float number.
- This filter removes all characters except numbers, + and – from the string.
- See the code below:
<?php $float="ajs23.5;*&+6"; echo filter_var($float,FILTER_SANITIZE_NUMBER_FLOAT); /* OUTPUT 235+6 */ ?>
<?php $float="ajs23.5;*&+6"; echo filter_var($float,FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION); /* OUTPUT 23.5+6 */ ?>
- Callback filter is a functionality provided for us to have full control on the filtering of data, because it allows us to use our user-defined functions for filtering.
- Let us see an example. The code is given below:
<?php function uppercase($s) { return strtoupper($s); } $s="Welcome to php."; echo filter_var($s,FILTER_CALLBACK,array("options"=>"uppercase")); /* OUTPUT WELCOME TO PHP. */ ?>
<?php class upper { function uppercase($s) { return strtoupper($s); } } $ss="Welcome to php."; echo filter_var($ss,FILTER_CALLBACK,array("options"=>array("upper"=>"uppercase"))); ?>
- As we used the functions filter_var() and filter_input() for a single variable or input, we can use filter _var_array () and filter_input_array () functions for number of variables and inputs.
- Let us see an example, the code is given below:
- We will validate the form shown in fig 1 using the filter_input_array() function.
<?php $filter=array( "name"=>FILTER_SANITIZE_STRING, "school"=>FILTER_SANITIZE_STRIPPED, "age"=>FILTER_SANITIZE_NUMBER_INT, "per"=>array("filter"=>FILTER_SANITIZE_NUMBER_FLOAT,"flags"=>FILTER_FLAG_ALLOW_FRACTION), "email"=>FILTER_VALIDATE_EMAIL, "url"=>array("filter"=>FILTER_VALIDATE_URL,"options"=>FILTER_FLAG_HOST_REQUIRED)); $filtered=filter_input_array(INPUT_POST,$filter); var_dump($filtered); ?>
Thus we studied how to validate and sanitize input accepted from the user to simplify the further functions that work on the input in this PHP Filters tutorial.