0

Is it possible force PHP only respond to ajax requests?? By setting headers or etc. for example we have this code:

if (str.length == 0) { 
    document.getElementById("txtHint").innerHTML = "";
    return;
} else {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
        }
    };
    xmlhttp.open("GET", "gethint.php?q=" + str, true);
    xmlhttp.send();
}

and we want to make an ajax request. Now when we type 'SITENAME.COM/gethint.php?q=' in browser it shows something. How to prevent this event? thanks.

  • Possible duplicate of http://stackoverflow.com/questions/8553611/verifying-xmlhttprequest-in-php – Lex Lustor Jan 30 '16 at 20:01
  • you can use post method i guess – Punit Gajjar Jan 30 '16 at 20:03
  • 1
    Why are you concerned that someone can put the url into a browser and see the contents? You do know that anything sent across the net can ultimately be examined at the destination? – Lee Taylor Jan 30 '16 at 20:06
  • But an AJAX request is being sent by a browser… If you hack any of the below solutions (which answer your question) you won't prevent anyone seeing the data because you can just as easily open the developer console and see it, or send crafted headers to spoof a request. You're more likely to break your application and give a false sense of security that your APIs are somehow "protected" with this method. – msanford Jan 30 '16 at 20:32

2 Answers2

5

You can't guarantee that somebody won't be able to access this on a non Ajax call, but the following could help prevent non-ajax requests:

if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) 
     && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    // more code here
}

HTTP headers are fairly easy to set, so it wouldn't be something to secure it... Only disallow the average user from hitting the page directly.

grepsedawk
  • 3,324
  • 2
  • 26
  • 49
0

You can try this.

if (strtolower(filter_input(INPUT_SERVER, 'HTTP_X_REQUESTED_WITH')) === 'xmlhttprequest') {
   // I'm AJAX!
}
Punit Gajjar
  • 4,937
  • 7
  • 35
  • 70