Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 1 of 1
12-03-2008, 07:27 AM #1
- Join Date
- Dec 2008
- Thanked 0 Times in 0 Posts
Getting only the fields and data types you expect from a POSTed HTML form
Here's a method I use to process incoming POSTed form fields. It has been pieced together into a technique from other ideas I've found.
Although I'm beginning to use PHP's filter more, this technique sticks around and I've used it on many big projects.
First in your form, define the fields you are expecting to receive from your FORM when someone submits it.
$PAGE1_FORM_FIELDS = array(
'first_name' => array('type' => 'string'),
'last_name' => array('type' => 'string'),
'country_id' => array('type' => 'int'),
'type_id' => array('type' => 'int'),
'is_name_visible' => array('type' => 'bool')
Each element in the PHP above also has an array with only one element in this example which is the type of data you expect each to be. The reason the 'type' is part of an array is in the future it can be extended to add further elements without rewriting the code.
Now that the program knows what fields you are expecting and their data types we can go about processing them. I do this so often I've created a function.
function clean_up_posted_form_array(&$POST_ARR, $FORM_FIELDS)
foreach ($FORM_FIELDS as $name => $sig)
$FORM["$name"] = trim(strip_tags(stripslashes($POST_ARR["$name"])));
Also, the settype will set the type of the variable you are working with. If your form had a dropdown box for country_id that could only pass a number between 1 and 250, and for some reason you got back a string like 'ducks' the settype would rewrite it to 0, an invalid number.
Using this technique you can get yourself an array from a POSTed form that only contains the fields you want, and only contains the datatypes that you expect.
Last edited by EfficiencyPro; 12-03-2008 at 07:31 AM.