Filter your variables easily but like a pro!
July 13, 2008
Filed under
Development, PHP
How painful input validation is! Think about all the possible threats, combination of threats… think with the users’ mind. It’s a pain. And usually who can write scripts which filters effectively the user inputs is considered a pro, without hesitation. Just because it’s hard to do it.
Take the following scenario: you have a text-field which accepts text as user comment. You don’t want to let the user to use HTML in the comment box, and definitely not to allow the user to put javascript in the comment.
So how do you sanitize the string you get? It’s a long and hard way. You would use RegExp to exclude some entities then some php inbuilt functions to encode the remaining or even better to strip tags.
I show you an easier way:
filter_var(’<script>alert('Hello');</script>', FILTER_SANITIZE_STRING);
Done, the <script> tags will be stripped so the string will arrive in the database as alert(’Hello World’).
There are many available filters, just to mention the most interesting ones:
- FILTER_SANITIZE_EMAIL — it sanitizes email address, strips characters which are not in conformance with the applicable RFC (link)
- FILTER_SANITIZE_URL — whether the URL from the variable is in conformance with the applicable RFC (link)
- FILTER_VALIDATE_IP — whether if the input is an IP address or not
I recommend using the filter_var() function and its filters for two obvious reasons: it saves you a lot of headaches and saves you time. Even though the filter_var function was introduced only in php 5.2 the function is extremely useful and gives another reason for you of why to upgrade to php5
For a complete reference please check php.net.
Possible related posts (automatic):
Related posts brought to you by Yet Another Related Posts Plugin.



















Comments
Tell us what you're thinking...
and oh, if you want a pic to show with your comment, go get a gravatar!
If you want to use your OpenID, fill out the field labeled "Website" with the OpenID URL. The other fields may remain empty.