结束答案googling了很多!
步骤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:现在,让我们保护ajax处理程序PHP文件,
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');
}
NOTE: SORRY FOR NESTED IF..ELSE, BUT IT INCREASES UNDERSTANDABILITY. YOU CAN SIMPLIFY ALL THREE IN ONE IF ELSE. 85% Security Enhanced !