HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI R GO KOTLIN SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING BASH RUST
PHP Filters
Validating data = Determine if the data is in proper form.
Sanitizing data = Remove any illegal character from the data.
The PHP Filter Extension
PHP filters are used to validate and sanitize external input.
The PHP filter extension has many of the functions needed for checking user input, and is designed to make data validation easier and quicker.
The filter_list() function can be used to list what the PHP filter extension offers:
ExampleGet your own PHP Server
| Filter Name |
Filter ID |
| int | 257 |
| boolean | 258 |
| float | 259 |
| validate_regexp | 272 |
| validate_domain | 277 |
| validate_url | 273 |
| validate_email | 274 |
| validate_ip | 275 |
| validate_mac | 276 |
| string | 513 |
| stripped | 513 |
| encoded | 514 |
| special_chars | 515 |
| full_special_chars | 522 |
| unsafe_raw | 516 |
| email | 517 |
| url | 518 |
| number_int | 519 |
| number_float | 520 |
| add_slashes | 523 |
| callback | 1024 |
Why Use PHP 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
You should always validate external data!
Invalid submitted data can lead to security problems and break your webpage!
By using PHP filters you can be sure your application gets the correct input!
ADVERTISEMENT
PHP filter_var() Function
The filter_var() function both validate and sanitize data.
The filter_var() function filters a single variable with a specified filter. It takes two pieces of data:
The variable you want to check
The type of check to use
Sanitize a String
The following example uses the filter_var() function to remove all HTML tags from a string:
Example
Hello World!Validate an Integer
The following example uses the filter_var() function to check if the variable $int is an integer. If $int is an integer, the output of the code below will be: "Integer is valid". If $int is not an integer, the output will be: "Integer is not valid":
Example
Integer is validTip: filter_var() and Problem With 0
In the example above, if $int was set to 0, the function above will return "Integer is not valid". To solve this problem, use the code below:
Example
Integer is validValidate an IP Address
The following example uses the filter_var() function to check if the variable $ip is a valid IP address:
Example
127.0.0.1 is a valid IP addressSanitize and Validate an Email Address
The following example uses the filter_var() function to first remove all illegal characters from the $email variable, then check if it is a valid email address:
Example
john.doe@example.com is a valid email address