在谷歌搜索了很多次后,回答结束了!
步骤1:为所有Web服务生成令牌系统:
生成令牌:
session_start();
$token = md5(rand(1000,9999)); //you can use any encryption
$_SESSION['token'] = $token; //store it as session variable
?>
步骤2:发送Ajax调用时使用它:
var form_data = {
data: $("#data").val(), //your data being sent with ajax
token:'<?php echo $token; ?>', //used token here.
is_ajax: 1
};
$.ajax({
type: "POST",
url: 'yourajax_url_here',
data: form_data,
success: function(response)
{
//do further
}
});
步骤3:现在,让我们用
session_start(); //most of people forget this while copy pasting code ;)
if($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {
//Request identified as ajax request
if(@isset($_SERVER['HTTP_REFERER']) && $_SERVER['HTTP_REFERER']=="http://yourdomain/ajaxurl")
{
//HTTP_REFERER verification
if($_POST['token'] == $_SESSION['token']) {
//do your ajax task
//don't forget to use sql injection prevention here.
}
else {
header('Location: http://yourdomain.com');
}
}
else {
header('Location: http://yourdomain.com');
}
}
else {
header('Location: http://yourdomain.com');
}
注意:对不起,如果…否则嵌套,但它增加了可理解性。
如果不是这样的话,你可以把这三个简化为一个。85%的安全性增强!