I've created a webapp using CodeIgniter. There are several places where I use ajax in the application.
I want to know if there is a way where I can stop direct access and query to the ajax controller and only allow legitimate ajax requests originating from the page to be processed.
Thanks.
Yes you can do this without a problem. The CodeIgniter input class has a method called is_ajax_request(). Simply check for this at the start of your controller action. For example:
function ajax_save() {
if ($this->input->is_ajax_request()) {
//continue on as per usual
} else {
show_error("No direct access allowed");
//or redirect to wherever you would like
}
}
If you have controllers that are designated completely for ajax calls, you can put that if statement into the constructor function __construct()
for the controller. Remember to call parent::__constructor() first though!
Edit: As for "originating from the page", you should probably be doing authentication + security checks (likely via session so that you don't hit the database) on your ajax request. So a rogue user not affiliated with your webapp shouldn't be able to send an ajax request manually anyways. Hope this answers your question.