views:

40

answers:

1

There are some scripts that I use only via ajax and I do not want the user to run these scripts directly from the browser. I use jQuery for making all ajax calls and I keep all of my ajax files in a folder named ajax.

So, I was hoping to create an htaccess file which checks for ajax request (HTTP_X_REQUESTED_WITH) and deny all other requests in that folder. (I know that http header can be faked but I can not think of a better solution). I tried this:

ReWriteCond %{HTTP_X_REQUESTED_WITH} ^$
ReWriteCond %{SERVER_URL} ^/ajax/.php$
ReWriteRule ^.*$ - [F]

But, it is not working. What I am doing wrong? Is there any other way to achieve similar results. (I do not want to check for the header in every script).

A: 

Just check for if($_SERVER['HTTP_X_REQUESTED_WITH']=='XMLHttpRequest'){ at the beginning of the document, if it's not set, then don't return anything.

edit Here's why: http://github.com/jquery/jquery/blob/master/src/ajax.js#L370

edit 2 My bad, just read through your post again. You can alternatively make a folder inaccessible to the web and then just have a standard ajax.php file that has include('./private/scripts.php') as your server will still be able to access it, but no one will be able to view from their browser.

Robert
I like the idea. However, I have to pass a parameter to the ajax call to distinguish which 'private' script to call. Since the ajax calls are spread in number of files, this is not practical in my particular case.
Vikash