Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to prevent AJAX pages from being viewed alone in a browser?

Tags:

ajax

security

php

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.

like image 411
alexcoco Avatar asked Aug 26 '10 23:08

alexcoco


3 Answers

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'].

like image 121
Daniel Vandersluis Avatar answered Nov 07 '22 02:11

Daniel Vandersluis


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.

like image 3
efritz Avatar answered Nov 07 '22 04:11

efritz


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
}
like image 2
Vaibhav Malushte Avatar answered Nov 07 '22 03:11

Vaibhav Malushte