CodeIgniter – Public Form Validation Callbacks
Filed under Tutorials
When using CodeIgniter you will most likely end up using the form_validation library and need to use a custom callback.
A possible custom callback might look something like:
class Some_class extends Controller
{
function index()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'trim|required|callback_username_check');
if($this->form_validation->run() == FALSE)
{
$this->load->view('login_view');
}
else
{
//Process login
}
}
function username_check($username)
{
//Check to see if username is in the database
}
}
Now if ‘Some_class’ was your default page what you may not realise is that if someone using your site were to navigate to ‘http://www.example.com/index.php/username_check’ the username_check function will be called. Now if someone typed in ‘http://www.example.com/index.php/username_check/some_name’ the username_check function would be called with the value of ‘some_name’.
This is most likely functionality you do not want your website to have. You cannot make the function private as that would mean that the form_validation library would not be able to access it. The solution is to precede the function name with an underscore.
function _username_check($username)
{
//Check to see if username is in the database
}
Simple. Just remember to update any references to the function in your code. Also note that when registering the callback with the form_validation library make sure to use ‘callback__username_check’ and not ‘callback_username_check’ (note the first one is a double underscore). Now even if a user types in ‘http://www.example.com/index.php/_username_check/some_name’ the function will not be called.
Aug20
August 20, 2010 at 10:56 pm
Personally I put my callbacks in a MY_Form_validation.php file in the /application/libraries/ folder, so I am sure they are not public even if I don’t privatize them.
One other possibility is to use PHP5 private word before the method :
private function my_callback() etc…
August 20, 2010 at 11:29 pm
Thanks for the input.
Putting the callbacks in a MY_Form_validation.php file should work like you say but unless something has changed since I last used CodeIgniter making the validation function in the controller private would make the validation function inaccessible to the form validation library.