Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is filter_var a good way to go?

Tags:

security

php

Is filter_var any good for filtering data? What kind of bad data will it filter? I do use mysql_real_escape_string but I wonder if adding filter_var will help?

like image 935
mikelbring Avatar asked Mar 18 '09 17:03

mikelbring


People also ask

What should the Filter_var () function be used on?

What is filter_var()? filter_var() is a PHP function used to filters a variable with the help of a specified filter. In PHP programming language we can use filter_var() function to validate and sanitize a data such as email id, IP address etc.

What is Filter_validate_email?

The FILTER_VALIDATE_EMAIL filter validates an e-mail address.

What is Filter_sanitize_string?

Definition and Usage The FILTER_SANITIZE_STRING filter removes tags and remove or encode special characters from a string.


1 Answers

To defend from SQL injection use prepared statements if possible. If not, use mysql_real_escape_string for strings, (int) casting or intval() for integers, (float) or floatval() for floats and addcslashes($input, '%_') for strings to be used inside LIKE statements. Things get even more complicated when trying to escape strings to be used inside RLIKE statements.

For filtering HTML content, the best would be strip_tags (without passing $allowable_tags), but... you may not like/want it, in which case the most affordable solution is:

$escaped = htmlspecialchars($input, ENT_QUOTES, $your_charset); 

A more reliable solution would be to use a library like HTML Purifier

Filter functions are OK, but some of them are more validators than filters. Depending on your needs you may find some of them useful.

like image 140
Ionuț G. Stan Avatar answered Sep 17 '22 19:09

Ionuț G. Stan