File access permission/deny function
Short version:


You may trust your own PHP code, if you write it well.
You should not trust data received by cookies, $_GET or $_POST.
Attempting to distinguish data sent from your JavaScript application from malicious input relies on methods that are both hard and easily bypassed.


Long version:

First of all, do you really need the ? true : false?
The == operator already returns a boolean.

Forbidding direct access is a complex (impossible?) task.
The user might just watch the web traffic you send your own Ajax application, and then imitate the output your app would send.

Even if you could prevent that, it'd probably still be pointless - the user could just edit the JavaScript code in many ways (so many in fact that it's probably worthless to try to detect them) so the application would be manipulated into doing what the "attacker" wants.

If you are not concerned about the current application user but rather protecting your user against third parties, then using HTTPS might be the best option. Why re-implement what's already available and designed by people who are - let's face it - smarter than both of us combined (and with the added advantage that it's been around for some time, so its flaws have already had more time to be detected and fixed!)

At some point you are using __FILE__ to detect if the code is authorized? Does this mean the attacker can directly execute PHP code on your server?
If not, then your __FILE__ check is worthless.
If so, then your __FILE__ check is still worthless, as the attacker can just directly call the file functions bypassing your whole security system.

Remember this:


Users can manipulate all sent data. Cookies, $_GET and $_POST data can all be manipulated by the user.
All data you send your client-side application can be inspected by the user. See Firebug for a good example. If you send some_hash to the client, the user has ways to find that out.
You may, however, protect your user against third parties.
Code that is executed in the client-side can be manipulated. HTML, CSS and JavaScript can all be edited.
Fortunately, those edits are local. Meaning that an user can change the JavaScript that's executed on his computer, but fortunately not the JavaScript that's executed in someone else's computer - provided the server is well implemented.


Ajax code is typically executed client-side (I'm going to bet it's also true in your case), so all your JavaScript can be modified. Your "receive token" function can just be modified to include an alert function.

function receive_token() {
    var key = ajax_request_token();
    //Code injected by the user
    alert(key);
    //End code injected by the user
    return key;
}


The user could then proceed to use your key token to pretend he's the application.

Not sure what you mean by "the file being included within another one".