How do I check if the request is made via AJAX in CodeIgniter?
In Codeigniter we can use
if(!$this->input->is_ajax_request()){ // check if request comes from an ajax
redirect(site_url('home'),'refresh'); // if the request is not coming from an ajax redirect to home controller.
}
I think you are basically looking to protect your ajax api's from being accessed directly by the users. You want users to be able to access ajax api's when invoked by your own code (javascript etc) but users should be denied access if they try to directly hit the api.
If you are still looking for a perfect solution (HTTP_X_REQUESTED_WITH is not always reliable, since your library might not support this. Even it might get stripped off by proxies if user is behind one) try to use crumbs to protect your ajax api's. Crumbs are used for flow validation, which make sure that users access the api's via a pre-defined/pre-decided flow and not directly.
As of Codeigniter 2.0 it is prefered to use $this->input->is_ajax_request()
If you are using a library that sends the X-Requested-With
header, then you can do...
if (strtolower(filter_input(INPUT_SERVER, 'HTTP_X_REQUESTED_WITH')) === 'xmlhttprequest') {
// I'm AJAX!
}