Forum Moderators: coopster

Message Too Old, No Replies

Form Validation + Sanitizing

         

ag_47

2:43 am on May 3, 2008 (gmt 0)

10+ Year Member



I need some feedback on how I'm trying to validate and clean up a form.
It contains a title, message, email, and website fields. I'm going to use the newer filter_input_array() function to do this. I'm using something like:

$filters = array(
"fptitle" => array ("filter" => FILTER_SANITIZE_STRING ),
"fpdata" => array ("filter" => FILTER_SANITIZE_STRING ¦ FILTER_SANITIZE_MAGIC_QUOTES),
"fpemail" => array ("filter" => FILTER_SANITIZE_EMAIL ¦ FILTER_VALIDATE_EMAIL),
"fpweb" => array ("filter" => FILTER_SANITIZE_URL ¦ FILTER_VALIDATE_URL),
);

$res = filter_input_array(INPUT_POST, $filters) or
exit("Failed to validate data!");

Is this ok? I haven't tested it very well yet..and I'm still a little confused how to put everything together. I'm trying to achieve the following:

1. Clean up any illegal characters with FILTER_SANITIZE, and if anything was updated - display the form again with the updated data and ask he user to very nothing went missing.
2. In addition to cleaning up, if anything is invalid, promt the user to fix it.
3. Once everything submitted is clean, only then i will store into a database.

I don't want to have a messy code, any advice? How should I go about analyzing $res.. (it's an array)

Thanks for reading.

coopster

6:37 pm on May 3, 2008 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



analyzing $res.. (it's an array)

Exactly. As you know it is an array so you can loop through the array and do your form validation, input "name" by input "name" until you are complete. Check each value returned for valid/invalid data and process accordingly.

ag_47

7:57 pm on May 3, 2008 (gmt 0)

10+ Year Member



Yes, I was just trying to figure out an efficient way to do this.
Just a heads up, applying more than one filter doesn't seem to work:

FILTER_SANITIZE_STRING ¦ FILTER_SANITIZE_MAGIC_QUOTES..

What I decided to do is use filter_input_array() to clean all special characters up. Then call it again to validate email + url, after which I can finally store it into the db.
Should I be encoding characters like &, %, <, > before storage?
How can I preserve line breaks in a textfield?

coopster

10:25 pm on May 3, 2008 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



applying more than one filter doesn't seem to work

No, but that would be nice. For now you can just use a

FILTER_CALLBACK
and in your user-defined function combine the filters and/or additional logic you need.