9

I have a page that loads other pages via Ajax (think frames, except without the frames).

Obviously these pages can all be called independently, so I want to detect if they are being called via the Ajax, and if not, redirect to the main Ajax page.

The pages are php pages, so I have access to that as well.

index:

    goto = "StandalonePrograms.php";
    var clear = "<br style='clear:both;'>"
    if(goto != ''){
        $.ajax({
            url: goto,
            context: document.body,
            success: function(data){
                $('#mainwindow').html(data + clear);
                $('#mainwindow').find("script").each(function(i){
                    eval($(this).text());
                });
            }
        });
    }
AndyD273
  • 7,177
  • 12
  • 54
  • 92
  • 1
    http://stackoverflow.com/questions/3696650/how-to-detect-if-file-is-being-accessed-or-requested see the selected answer – Kevin B Mar 22 '12 at 18:38
  • 1
    Have the AJAX request call the page with a special query string. It's not foolproof, but it might be good enough. – Blazemonger Mar 22 '12 at 18:39
  • possible duplicate of [How do I check if the request is made via AJAX with PHP?](http://stackoverflow.com/questions/4301150/how-do-i-check-if-the-request-is-made-via-ajax-with-php) – Marc B Mar 22 '12 at 18:39

2 Answers2

16

Modern browsers add the following request header when a request is made using the XMLHttpRequest object:

X-Requested-With: XMLHttpRequest

In PHP, check the existence of this header using:

$_SERVER['HTTP_X_REQUESTED_WITH']
Rob W
  • 341,306
  • 83
  • 791
  • 678
-1

You cannot never trust clients and their sent information! The headers can be spoofed by hackers (for example with cURL) and even HTTP_X_REQUESTED_WITH is not reliable. there is no 100% trusted way to know that. The Only way is using captcha...