Check for Ajax request in Code Igniter

From: http://stackoverflow.com/questions/11687180/check-for-ajax-request-in-code-igniter

Q:

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 :

define('IS_AJAX', 
       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?

A:

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

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

發表迴響

在下方填入你的資料或按右方圖示以社群網站登入:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / 變更 )

Twitter picture

You are commenting using your Twitter account. Log Out / 變更 )

Facebook照片

You are commenting using your Facebook account. Log Out / 變更 )

Google+ photo

You are commenting using your Google+ account. Log Out / 變更 )

連結到 %s