How do I prevent my users from accessing directly pages meant for ajax calls only?

Passing a key during ajax call seems like a solution, whereas access without the key will not be processed. But it is also easy to fabricate the key, no? Curse of View Source...

p/s: Using Apache as webserver.

EDIT: To answer why, I have jQuery ui-tabs in my index.php, and inside those tabs are forms with scripts, which won't work if they're accessed directly. Why a user would want to do that, I don't know, I just figure I'd be more user friendly by preventing direct access to forms without validation scripts.


Don't worry about user friendlyness in this case. In fact, I'd say you're better off to fail early than try to make it pleasant. For example, say you have it redirect to index.php for non-AJAX visits. Result: someone is guaranteed to bookmark the AJAX script since it gets them to your home page.

Written by Kirk Strauser

Accepted Answer

As others have said, Ajax request can be emulated be creating the proper headers. If you want to have a basic check to see if the request is an Ajax request you can use:

 if($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {
     //Request identified as ajax request

However you should never base your security on this check. It will eliminate direct accesses to the page if that is what you need.

Written by Eran Galperin
This page was build to provide you fast access to the question and the direct accepted answer.
The content is written by members of the community.
It is licensed under cc-wiki