How do I check if the request is made via AJAX in CodeIgniter?

How do I check if the request is an AJAX? I am using CodeIgniter. I have a link that when it clicked, it'll open the pop-up dialog window this is done through ajax it requests to a controller name login_window() .

CodeIgniter

//Here is the controller name:
function login_window(){
    // request via ajax
    $this->load->view("login_window");
}

jQuery

//here is the jquery code:
//I am using a jquery plugin FACEBOX

$('a[rel*=dialog]').facebox();

<a href="http://localhost/codeigniter/login_window" rel="dialog">Login</a>

I want to check if it is an AJAX request and if not, i will redirect them to homepage. so there's no way they can access the page that is intended only for ajax requests.


如果您正在使用发送X-Requested-With标头的库,那么您可以这样做...

if (strtolower(filter_input(INPUT_SERVER, 'HTTP_X_REQUESTED_WITH')) === 'xmlhttprequest') {
   // I'm AJAX!
}

至于Codeigniter 2.0,最好使用$this->input->is_ajax_request()


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.

链接地址: http://www.djcxy.com/p/57622.html

上一篇: 是否可以写严格类型的PHP代码?

下一篇: 如何检查请求是否通过CodeIgniter中的AJAX进行?