PHP & Militarizing input variables ..

While pondering good material to actually write about, I was going through a PHP library I had written a while back. Some simple possibly overkill variable validation routines to verify what I was passing was truly intended.

The library made use of a small set of utility functions. The library was called militarized.php some basic examples of what it had were defined as ..

militarize_integer($integer, $min, $max)
militarize_string($integer, $min_len, $max_len)
militarize_set($integer, $min_len, $max_len, $expected)
demilitarize_integer($integer, $min, $max)
demilitarize_string($integer, $min_len, $max_len)
demilitarize_set($integer, $min_len, $max_len, $expected)

Each of these functions were used at the beginning of a library function that HAD to have trusted variables such as …

function fetchUserDetails($uid) {
$uid = demilitarize_integer($uid, 1, 100000); // arbitrary maximum of 100000 users
$q = “select * from users where uid=’$uid’”;
}

The idea here was a militarized variable was expected, and was formated as an associative array with the keys ‘mil’, ‘value’ , ‘min’, and ‘max’ – obviously you couldn’t just use the variable in your code ‘as is’ when passed you had to demilitarize it, and second if you didn’t pass the right type, your code would fail. The code would also fail if the variable did not pass certain tests. For integers this would be a range, for strings this would be length, and for a set this would be length and the presence of said string in an array

Using this library also helped in asserting, during development, your intentions, because you had to call the function using the militarize_XXX routine as in :

fetchUserDetails(militarize_integer($_GET['uid'], 1, 100000));

So, what does everyone think about this? Simple enough, and very assertive as to what you intend to do, Is this overkill or do you think its appropriate? This does double up quite a lot in actually testing variables, as an integer variable with range 1-10 does not match an integer variable with a range 1-100 – I never completed coding the tests for sets to have comparitive arrays, I just checked the presence during the demilitarized side of things. I also hardly used sets anyway, and ended up using integers where possible. The only place I can remember using a set of strings was where the user could create the list of keys theirselves and the list was dynamic. I would fetch the list assert the value was in the list, and push it through..

Share