AJAX only access

Solution 1:

You cannot reliably prevent this from happening. The key really is not to consider someone accessing this file directly as a security issue - plan for this being possible and you will be in a much more secure place.

Some people might recommend code that looks like this (or similar):

if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) 
     && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    // more code here
}

However, the fact of the matter is that HTTP headers can be spoofed quite easily and are not a means of securing code. In my testing on a busy site a while back i noticed that these headers are not actually that reliable anyway.

Solution 2:

As other people have suggested in their replies, this is not possible. This is because of one of the pillar principles of computer security: you can never trust the client. This is why we validate all input from the client, etc.

Instead of trying to block other clients from accessing your services, instead spend time writing defensive web services. Meaning, make sure that malicious users can't slip injections or other attacks through your business logic. Ex., make sure all e-mails are valid, people aren't buying items for negative dollars, etc.

Oh, and the fact that web services are open is a GOOD THING! You're providing a open API to your users, which is very neat! Maybe instead of trying to lock out your community you embrace it - give them some documentation on how to interface with your services and they'll make more clients. Instead of you buying the iPhone SDK and spending time learning Objective C, one of your users might.