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.
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']
.
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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With