Reputation: 612
I have a utilitypage.php that writes some database info. I call this PHP page via AJAX from mysite.com/mypage.html.
If some malicious visitor looks at the source code and finds the name of the php page being called, they can then go to that page directly or call it from some other site.
How can I ensure that utilitypage.php can only be called from mysite.com/mypage.html? (detect if it's called from elsewhere)
I looked at some $_SERVER variables but see they are not always reliable. The visitors to mypage.html are not authenticated users.
Thanks!
Upvotes: 0
Views: 395
Reputation: 5220
A really simple (but possibly unreliable) way is to check the headers:
$isAjax = isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND
strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest';
but they can be spoofed, so don't rely solely on them.
But as is stated here by Chris
There isn't any absolutely foolproof method to prevent this, since any header information can be spoofed. Session-based tokens are another possible solution, but in that case your javascript is publicly accessible, so anyone who wanted to spend a little time could determine how your token system works and figure out a way around it.
The only way to make sure is to give each user a unique token and store it in their session. Then, just pass this token back when you make an ajax request and ensure it matches so you know the request is legit.
Check this out for more info http://en.wikipedia.org/wiki/Cross-site_request_forgery
Upvotes: 2