CodeIgniter Forums
Validation of controller parameters? - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived General Discussion (https://forum.codeigniter.com/forumdisplay.php?fid=21)
+--- Thread: Validation of controller parameters? (/showthread.php?tid=9318)



Validation of controller parameters? - El Forum - 06-21-2008

[eluser]degu[/eluser]
Hello,

What are the best practices regarding controller parameters validation in CodeIgniter? If I'm not mistaken, Checking the type of passed data in routes.php with :num or regular expressions isn't enough. Data can still be passed directly to the controller's url.

So how do you validate controller parameters in CodeIgniter? Are there any helper functions? I couldn't find anything in the user guide or forum.

Thanks a lot!


Validation of controller parameters? - El Forum - 06-21-2008

[eluser]xwero[/eluser]
You can use the same does-it-exist approach that the controller and method use.

For database values i have written an abstracted method and put in a basemodel where all other models are children of.
Code:
function _exists($table,$value,$field = 'id')
{
    $this->db->where($field,$value); // not chained for php4 compatibility and readability
    return ($this->db->count_all_results($table) == 0)?FALSE:TRUE;
}
Now you have a very flexible function that can be used in any model with data shown in the url.

If the segment can only be a few values you extend the url helper with this function
Code:
function url_enum($segment,$redirect,$enum)
{
   if( ! in_array($segment,$enum){ redirect($redirect); }
}
In your controller methods you can then do something like
Code:
function somepage()
{
    $enum = array('ok','good','fine');
    url_enum($this->uri->segment(3),'',$enum);
    
    // is_rating is based on the _exists function
    // is_rating parameter one is the position of the segment, for flexibility reasons
    // the second parameter is for the same reason as in the url_enum function, to redirect the page
    $this->somemodel->is_rating(4,$this->uri->segment(3));
}
These two helpers will validate almost all parameter segments.


Validation of controller parameters? - El Forum - 06-21-2008

[eluser]degu[/eluser]
Thanks xwero, that makes sense. You said you are using a base model class. Do you have to load a base model before it can be used as a parent class? If so, where and how (I assume the PHP file with the base class must be included manually before it can be used, but where is best place in CI to do this)?