Does $_SERVER['HTTP_X_REQUESTED_WITH'] exi

2019-01-01 10:45发布

All over the Internet, included even here at Stack Overflow, people state that a good way to check if a request is AJAX or not is to do the following:

if (strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest' ) {...}

However, I don't see $_SERVER['HTTP_X_REQUESTED_WITH'] in the official PHP documentation

And when I try to do the following:

echo $_SERVER['HTTP_X_REQUESTED_WITH'];

Nothing is outputted.

Am I doing something wrong? Because I'd really like to be able to use $_SERVER['HTTP_X_REQUESTED_WITH'] if it's available.

10条回答
明月照影归
2楼-- · 2019-01-01 11:20

Here's a quick function with example usage:

function isXmlHttpRequest()
{
    $header = isset($_SERVER['HTTP_X_REQUESTED_WITH']) ? $_SERVER['HTTP_X_REQUESTED_WITH'] : null;
    return ($header === 'XMLHttpRequest');
}

// example - checking our active call
if(!isXmlHttpRequest())
{
    echo 'Not an ajax request';
}
else
{
    echo 'is an ajax request';
}
查看更多
若你有天会懂
3楼-- · 2019-01-01 11:20

You can also blame some browser bugs - see this question and its solution for Firefox

Firefox does not preserve custom headers during Ajax request redirect: an ASP.NET MVC solution

IE also having caching issue which is more serious then detection of request method.

You anyway needs to add cache busters to avoid caching, so why not use another flag to specify the ajax call - or more better you can use different URL like http://ajax.mysite.com/endpoint/sevice?params

查看更多
公子世无双
4楼-- · 2019-01-01 11:26

This header is a standardization-in-progress from all of the AJAX libraries out there.

It won't be documented in the php documentation per-se, but rather in the different AJAX libraries that set this header. Common libraries do sent this header: jQuery, Mojo, Prototype, ...

Usually these library will set the header using

xhrobj.setRequestHeader("X-Requested-With", "XMLHttpRequest");
查看更多
忆尘夕之涩
5楼-- · 2019-01-01 11:26
$headers = apache_request_headers();
$is_ajax = (isset($headers['X-Requested-With']) && $headers['X-Requested-With'] == 'XMLHttpRequest');
查看更多
孤独寂梦人
6楼-- · 2019-01-01 11:33

$_SERVER keys that start with HTTP_ are generated from HTTP request headers. In this case, the X-Requested-With header.

查看更多
低头抚发
7楼-- · 2019-01-01 11:35
echo $_SERVER['HTTP_X_REQUESTED_WITH'];

What'd you expect from such a code? Assume you're running it directly from the browser, not using AJAX request. So, how come this header could be set?

Well the Answer to the Ultimate Question of Life, the Universe, and Everything - an HTTP sniffer! Get yourself one and forget of printing $_SERVER variable.

Firebug has one, or you may want to use Fiddler HTTP proxy or LiveHTTPHeaders Mozilla plugin. I'm bored to make links but it easily googled.

So, with HTTP sniffer you can be sure of any HTTP header ever.

Note that you can't prevent any "direct access" by using XHR, as every HTTP request to your server is already "direct".

查看更多
登录 后发表回答