In reality, one of the most robust filters included with the filter library is the one responsible for sanitizing strings, since it’s capable of doing this in several ways. To understand more clearly how this filter works with the numerous optional arguments, below I coded a few basic examples that show it in action in diverse cases. Take a look at them: // example on sanitizing strings in a basic way $string = '<script>alert('hello');</script>'; echo filter_var($string, FILTER_SANITIZE_STRING); // quotes are encoded
// example on sanitizing strings using the FILTER_FLAG_NO_ENCODE_QUOTES argument $string = '<script>alert('hello');</script>'; echo filter_var($string, FILTER_SANITIZE_STRING, FILTER_FLAG_NO_ENCODE_QUOTES); // quotes are not encoded
// example on sanitizing strings using the FILTER_FLAG_STRIP_LOW argument $string = '<script>#$%^&!*</script>'; echo filter_var($string, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW); // strips low characters
// example on sanitizing strings using the FILTER_FLAG_STRIP_HIGH argument $string = '<script>This is a string#$%^&!*</script>'; echo filter_var($string, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH); // strips high characters As shown above, the FILTER_SANITIZE_STRING filter has the ability to clean up strings in many different fashions. Now, speaking more specifically, the first case will encode the single quotes included within the sample literal, while the second example will behave the opposite way -- that is, it won’t encode the quotes, since the FILTER_FLAG_NO_ENCODE_QUOTES has been passed to the “filter_var()” function. Finally, the last two code snippets show how to use the filter for removing high and low ASCII characters from the supplied string, according to the option specified in each case. In addition, here are a few more examples that demonstrate how to sanitize different strings by removing the high and low ASCII characters included within them: // example on sanitizing strings using the FILTER_FLAG_ENCODE_LOW argument $string = '<script>This is a string#$%^&!*</script>'; echo filter_var($string, FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_LOW); // encodes low characters
// example on sanitizing strings using the FILTER_FLAG_ENCODE_HIGH argument $string = '<script>This is a string#$%^&!*</script>'; echo filter_var($string, FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_HIGH); // encodes high characters
So far, nothing unexpected, right? As you saw earlier, the FILTER_SANITIZE_STRING filter can be used in different ways to remove and encode specific characters in a specific string. However, the filter is capable of doing a few more useful things with literals. So, in the last section of this tutorial I’m going to show you how to use it for sanitizing email addresses, as well as float and integer numbers. Thus, to see how this will be accomplished click on the link below and read the following segment.
blog comments powered by Disqus |
|
|
|
|
|
|
|