-1

when use GET Method for receive JSON data , we can acsses the result directly from web browser , for example i send a mydata value from ajax to a main.php file and it process and get answer show a result some thing like below :

<?php 

if (isset($_GET["mydata"])) {
if ($_GET["mydata"]=="hello"){
echo "hello world";

} 
}

?>

but when a user call it in browser directly like http:mysite.com/mydata.php?mydata=hello recive answer . i want dont allow users to get answer of http request directly , and just can show it from ajax result of main page is it possible ?

user3717270
  • 97
  • 2
  • 8
  • I don't think it is possible to completely prevent users from accessing that page directly - you could for example check whether the `Referer` header has been sent (which would be if the page were accessed as a result of an AJAX call), but advanced users could easily bypass that. – rhino Jun 08 '14 at 11:43
  • how can send data from my web part safely like that ? – user3717270 Jun 08 '14 at 11:48
  • Define what a "user" is. To your server, a "user" is anything that sends an HTTP request. Anything can send an HTTP request. There's no difference between an HTTP request sent as AJAX or by hand. You cannot hide the details of an HTTP request to a public API. Why do you want to do this in the first place? What do you have to protect? – deceze Jun 08 '14 at 12:03

1 Answers1

1

You're asking how to prevent an ajax-only request from being accessed directly by copy-pasting the URL into the web browser; that is, only allowing the URL to be accessible via ajax on the main web page.

Well, there are a few things you can try:

  1. Check the Referrer for the URL of the main page with $_SERVER['HTTP_REFERER']
  2. Set a header in Javascript using xhr.setRequestHeader() and then ensure it's value by checking for $_SERVER['HTTP_X_....'] in PHP
  3. Like Jay Bhatt recommended, check for the X_REQUESTED_WITH header, but be aware this might not always be set (see: X-Requested-With header not set in jquery ajaxForm plugin)

However, in any of these situations you should be aware that anyone who knows what they are doing can easily set any HTTP header, variable, or even modify the referrer which is sent to the server. As such, there is no 100% guarantee that your resouce can be accessed only via AJAX on the main web page. There is no control built in the internet to verify where a request is coming from, so anyone can easily spoof or fake it.

Community
  • 1
  • 1
cegfault
  • 6,442
  • 3
  • 27
  • 49