Check for Ajax request in Code Igniter



I’m in a PHP script and I want to check whether the request is an Ajax request. (basically so as NOT to allow direct script access, other than Ajax call that is…)

So, I’m defining IS_AJAX somewhere in the main index.php file :

       isset($_SERVER['HTTP_X_REQUESTED_WITH']) && 
       strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');

And then checking it at the top of my script :

if (!IS_AJAX) exit('No direct script access allowed');

Since I’m new to CodeIgniter, I’m not really sure…

  • Is there any such built-in functionality?
  • Is there a more… elegant way to do it?


You can use $this->input->is_ajax_request() from the input class:

if (!$this->input->is_ajax_request()) {
    exit(‘No direct script access allowed’);