keepyourweb keepyourweb - 1 year ago 116
PHP Question

How to detect ajax cross domain request in php

For the normal ajax request I use:

strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'

But this don't work with cross domain request.

How can I do?

Answer Source

Edit2: If you're using jQuery.ajax function in this way:

var request = $.ajax({
url: "",
dataType: "jsonp",
jsonp: 'callback',
success: function(data) {

Then you can check the $_SERVER['REQUEST_URI'] variable, or simply $_GET['callback'] and $_GET['_']. The REQUEST_URI will look like this:


Edit: The answer below is to find out if it is cross-domain or not, not checking if it is AJAX

The answer to the question "How to determine if an ajax-call is from a different domain" is this:

I'm using the jQuery.ajax call, and for me using the variable $_SERVER['HTTP_REFERER'] works fine.

If I'm using a page on my local computer, this superglobal returns an empty string.

If I'm using a page on the internet, the value of $_SERVER['HTTP_REFERER'] returns the URL of the page that made the ajax call. So checking the value of this can tell you what you need to know.