简体   繁体   中英

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?

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

var request = $.ajax({
url: "http://somesite.com/somescript.php?somevar=somevalue",
dataType: "jsonp",
jsonp: 'callback',
success: function(data) {
alert('Done!');
}
});

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

/somescript.php?somevar=somevalue&callback=jQuery172028849187534502896_1333494007273&_=1333494443880

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.

To detect Ajax and CrossDomain Request try this:

function is_ajax_request() {
    return isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) ? $_SERVER['HTTP_X_REQUESTED_WITH'] : false === 'XMLHttpRequest';
}


function check_cross_domain($referrer, $host) {
    $referrer = str_ireplace( 'www.', '', parse_url( $referrer, PHP_URL_HOST ) );
    $pattern = '/' . $host . '/';
    return preg_match($pattern, $referrer);
}

使用 $_SERVER['HTTP_ORIGIN'] 获取请求域

you can use php's getallheaders() function. you can check the host entry

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM