Chapter 9: Security and Performance
270
Did you notice that at the end of updateUser() , the $_POST[‘id’] is escaped? You ’ re going to do the
same thing with the incoming $id on deleteUser() :
function deleteUser($id){
$data = array(‘status’ = > ‘inactive’);
$this- > db- > where(‘id’, $this- > db- > escape($id));
$this- > db- > update(‘admins’, $data);
}
Why are you escaping the incoming ID? Well, it ’ s coming from the URI, which can be manipulated by
the user. It ’ s very easy for a user to add other content to the URI (e.g., a series of SQL commands) and try
to affect your application.
Is this all you could be doing with these functions? Of course not! You can increase security until you
restrict activity down to a very small subset of activities. For example, it might be a good idea to limit all
incoming IDs to a length of 11 characters and to being an integer. Similarly, it would be a good idea to
restrict other fields down to their max size in the database. Why 11 characters? Well, this is an arbitrary
limit, some might say, but it really isn ’ t. It ’ s keyed to the maximum length of the INT type key field in
your database. Limiting it to integers keeps other nasty things from happening, such as trying to pass in
alpha characters or floating point numbers, or worse, hexadecimal characters.
Because these kinds of operations become tedious if done over and over again, you ’ re going to take
advantage of a CodeIgniter 1.6 feature that allows you to create your own helper functions. All you need
to do is create a file called MY_security_helper.php in /system/application/helpers. Any functions you
declare there will be added (or replace existing) functions in the Security helper.
In your new helper, you ’ re going to create two functions. The first, id_clean() , will determine whether
a passed - in ID is actually numeric and chop it down to a determined size. The second, db_clean() , will
run xss_clean() on a string and also chop it down to a determined size.
These two functions are both extremely simple functions, but they allow you to do a lot of heavy lifting:
< ?php
function id_clean($id,$size=11){
return intval(substr($id,0,$size));
}
function db_clean($string,$size=255){
return xss_clean(substr($string,0,$size));
}? >
The beauty of the intval() function is that it will render any non - zero - length string it encounters into
an integer. For example, it converts the hexadecimal number 0x1A into the integer 26, and the floating
point number 1.3333928920 into the integer 1. By further chopping it down to size with substr() , you
reduce the chances of a buffer overflow attack or other similar malicious mischief.
With these two functions in place, you can transform and simplify your MAdmins model thus: