简体   繁体   English

如何在php中检测ajax跨域请求

[英]How to detect ajax cross domain request in php

For the normal ajax request I use:对于我使用的普通 ajax 请求:

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: Edit2:如果您以这种方式使用 jQuery.ajax 函数:

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['_'] .然后你可以检查$_SERVER['REQUEST_URI']变量,或者只是$_GET['callback']$_GET['_'] The REQUEST_URI will look like this: REQUEST_URI 将如下所示:

/somescript.php?somevar=somevalue&callback=jQuery172028849187534502896_1333494007273&_=1333494443880 /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编辑:下面的答案是找出它是否跨域,而不是检查它是否是AJAX

The answer to the question "How to determine if an ajax-call is from a different domain" is this: “如何确定 ajax 调用是否来自不同的域”这个问题的答案是:

I'm using the jQuery.ajax call, and for me using the variable $_SERVER['HTTP_REFERER'] works fine.我正在使用 jQuery.ajax 调用,对我来说使用变量$_SERVER['HTTP_REFERER']工作正常。

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.如果我使用的是 Internet 上的页面,则$_SERVER['HTTP_REFERER']值返回进行 ajax 调用的页面的 URL。 So checking the value of this can tell you what you need to know.所以检查 this 的值可以告诉你你需要知道什么。

To detect Ajax and CrossDomain Request try this:要检测 Ajax 和 CrossDomain 请求,请尝试以下操作:

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.您可以使用 php 的 getallheaders() 函数。 you can check the host entry您可以检查主机条目

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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