Home > Backend Development > PHP Tutorial > javascript - PHP如何判断一个请求是否来源于本域并且是ajax请求?

javascript - PHP如何判断一个请求是否来源于本域并且是ajax请求?

WBOY
Release: 2016-06-06 20:36:12
Original
1162 people have browsed it

PHP如何判断一个请求是否来源于本域并且是ajax请求?

回复内容:

PHP如何判断一个请求是否来源于本域并且是ajax请求?

jquery中对于ajax是这样写的,xhr对象有setRequestHeader这个方法,设置头部:

<code>if ( !options.crossDomain && !headers["X-Requested-With"] ) {
    headers["X-Requested-With"] = "XMLHttpRequest";
}
// Set headers
for ( i in headers ) {
    xhr.setRequestHeader( i, headers[ i ] );
}
</code>
Copy after login

所以如果在PHP端验证的话,是这样的:

<code>public static function isAjax() {
   return 'XMLHttpRequest' == @$_SERVER['HTTP_X_REQUESTED_WITH'];
}
</code>
Copy after login

<code>if ( !isset($_SERVER['HTTP_X_REQUESTED_WITH']) || $_SERVER['HTTP_X_REQUESTED_WITH'] !== 'XMLHttpRequest' ) {

}
</code>
Copy after login

通过请求头的Referer属性可以获取来源,X-Requested-With属性(不代表ajax一定需要这个请求头属性)可以判断是否是ajax。但是请求头这种东西,你也知道的,很容易伪造。如果仅仅是做业务上的判断,请求头就够了,若果进行安全反爬等方面讲,这个就弱的一塌糊涂

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template