views:

241

answers:

3

I have a page that is loaded within another page using jQuery. What I wanted to know is if it is possible to somehow block direct access to that page that gets loaded within another page.

+2  A: 

You can try adding some magic value, to your get/post or cookie. Then check that value at the start of your page, and return some error page if it's missing.

However, that will NOT prevent some user from doing exactly that. if they debug your requests, for example with Firebug, then they can replicate the request with that magic number.

Am
A: 

You can't block it 100% -- requests from jQuery are normal browser requests, so the most you can do is prevent external linking and casual access (someone who goes to the trouble to completely duplicate the HTTP request will still be able to hit the page; there's no way around that).

You can stop external linking by checking the HTTP "referer" header and making sure the referring page is yours.

You can also check to see if a particular request is coming from jQuery vs. the browser by checking the header "X-Requested-With" -- jQuery adds this header and populates it with the value "XMLHttpRequest"; a regular browser request won't have that header.

You could also set up a verification system with cookies, expiring tokens that must be part of the request, etc.. but that's a lot more work and (I think) overkill -- if someone's determined to access the page directly and can get around the HTTP header filtering, they can also figure out your tokens.

Rob Whelan
A: 

Quoting Eran Galperin from a similar discussion

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.

Please take this answer by Jeremy Ruten also into account:

There is no way of guaranteeing that they're accessing it through AJAX. Both direct access and AJAX access come from the client, so it can easily be faked.

Why do you want to do this anyways?

If it's because the PHP code isn't very secure, make the PHP code more secure. (For example, if your AJAX passes the user id to the PHP file, write code in the PHP file to make sure that is the correct user id.)

More clever thoughts in the discussion linked above.

middus