Monday 2 February 2015

FILTER_SANITIZE_STRING in PHP

FILTER_SANITIZE_STRING

We can sanitize a string by using FILTER_SANITIZE_STRING which removes different tags and quotes to make the string safe for use. The id of this is 513. Let us start with an example.
$str="Welcome <script> alert('Hi plus2net')</script>"; 
$str1 = filter_var($str,FILTER_SANITIZE_STRING);
echo $str;
echo "<br>";
echo $str1;
For comparison we have displayed the original string and the string after using FILTER_SANITIZE_STRING function. You can see how the string is cleaned by removing the html tags and the quotes are also removed. Above example is a code visitors can use to post malicious codes to your system. We can sanitize such strings before using them.

FILTER_FLAG_NO_ENCODE_QUOTES

If we don't want to remove the quotes then we can add the flag FILTER_FLAG_NO_ENCODE_QUOTES like this
$str="Welcome <script> alert('Hi plus2net')</script>"; 
$str1 = filter_var($str,FILTER_SANITIZE_STRING,FILTER_FLAG_NO_ENCODE_QUOTES);
echo $str;
echo "<br>";
echo $str1;
IN addition to above we can also add few more flags like this
FILTER_FLAG_STRIP_LOW  Removes ASCII value less than 32 including tab & line breaks
 FILTER_FLAG_STRIP_HIGH  Removes chars having ASCII value more than 127
 FILTER_FLAG_ENCODE_LOW Encode ASCII less than 32
 FILTER_FLAG_ENCODE_HIGH Encode ASCII more than 127
 FILTER_FLAG_ENCODE_AMP Encode Chars to & amp;

0 comments:

Post a Comment