Jump to content

Filters Vs. Reg Expression


Zaper Gallis

Recommended Posts

K, I can't find any clear explanation or tutorial on the filter functions and I'm confused. When I first started writing my scripts the tutorials I found used reg expressions to remove special characters and validate emails. However from my understanding the PHP filter functions are a better way to go. So which should I use? And what exactly does the filters and flags remove? I can find lots of site saying "FILTER_FLAG_STRIP_LOW - Strip characters with ASCII value below 32" but I have no idea what characters that actually removes. Does it remove all the special charters? Or should I use FILTER_FLAG_STRIP_HIGH, or do I need them both? maybe nether of them are needed to safely sanitation a script? Does some one know of an easy to follow list on exactly what these flogs remove so I know? Can some one please better explain this to me? Thanks.

Link to comment
Share on other sites

Filters are just more... convenient than having to construct a regular expression for the cases they cover. Also, you'd hope that the PHP developers got the pattern matching right, so it eliminates the possibility of you making a mistake. The ASCII characters below 32 are the control codes - the characters that represent newlines and tabs, for example, and also some that have no meaning nowadays. If you want just "visible" characters, then you want to strip those. For sanitation purposes, however, it depends on what sort of script you are planning to construct — for example, if you were making an SQL query, then it would be much better to use mysql_real_escape_string(). Of course, there are only a limited number of filters so for everything else, you'd still need to use your own regular expressions.

Link to comment
Share on other sites

K, I understand that. Lets say I'm making a sign up and log in system. Would the following code remove all special characters from the username? Then safely allow them, but not allow scripting tags in the password? Or is there a better way to do so?

$username= filter_var($_POST['username'], FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW, FILTER_FLAG_STRIP_HIGH);$password= rtrim(mysql_real_escape_string(strip_tags($value)));

Then for sanitizing input for most all other uses I've created the following function, were I pass an array in for $input:

foreach ($input as &$value){$value = rtrim(mysql_real_escape_stringhtmlentities($value)));}

Would a filter be a smart way to do this? And one more thing. Is it safe to compare the orignal input value to another value, such as

 if ($_POST['username'] != filter_var($_POST['username'], FILTER_SANITIZE_STRING)){Error}

Or does this leave an opening to inject code into the script? If so how would I check if the input is the same after filtering it? Thanks for your time and help.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...