Welcome Guest, Not a member yet? Register   Sign In
Validation of controller parameters?
#1

[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!
#2

[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.
#3

[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)?




Theme © iAndrew 2016 - Forum software by © MyBB