tags:

views:

90

answers:

5

For example, when I want to update a part of my page with AJAX I would normally make the appropriate call to getPost.php which would return the markup to be inserted into my page. Is there any way to prevent a user from accessing this page directly (eg: example.com/getPost.php with the appropriate GET or POST arguments) and getting only part of the page since this should be used with AJAX as part of a whole, not alone?

I don't think permissions can be set on the file since it's the client requesting the page but is there a way to do this by passing an extra argument that can serve as a check digit of sorts.

+2  A: 

You can check the $_SERVER['HTTP_X_REQUESTED_WITH'] header. It should be equal to the value 'XMLHttpRequest' if it is an Ajax request.

Edit - like Daniel Vandersluis said, there is no way to fully enforce this. You can spoof user agent, referrer - anything that comes in with the request.

efritz
+6  A: 

You could take a look at the request headers and enforce that a header must be set for AJAX requests (often people use X-Requested-With with a value like XMLHttpRequest). Be aware that this header won't be set unless you set it yourself when you make your AJAX request (or use a Javascript library that does it automatically). However, there is no way to guarantee that someone wouldn't add in that header on their own if they wanted to.

The X-Requested-With header value can be found in $_SERVER['HTTP_X_REQUESTED_WITH'].

Daniel Vandersluis
Thanks for the quick answer, I didn't know about this!
alexcoco
+1  A: 

Since there's no way to be 100% sure who is asking the question, you can restrict the question itself.

The implementation of this will depend on the page of course.

For example let's say you're running curl command on a url, you can restrict the incoming variable to only a certain domain.

<?php
if (substr($_GET["url"], 0, 19) !== "http://example.com/")
{
    die();
}
// otherwise carry on
?>
Peter Ajtai
+1  A: 

shouldn't this work?

if(preg_match("/getPost\.php/", $_SERVER['PHP_SELF'])){
     // Access to file directly, quit..
     die();
}
cragiz
From the manual: `$_SERVER['PHP_SELF'] in a script at the address http://example.com/test.php/foo.bar would be /test.php/foo.bar.`... which doesn't really help, since it just gives the AJAX page. The script being called is the AJAX page, not the original requesting page.
Peter Ajtai
+1  A: 

what ever you request to server, it store the information in $_SERVER variable

to check what information this variable stores try this

print_r($_SERVER);

//you will see the difference in http and ajax request 

use this variable to check as bellow

if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) &&
    strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
   //ajajx request
}
else {
   //not an ajajx request
}
Vaibhav Malushte