Заключенный ответ после многократного поиска в Google!
Шаг 1: Создание системы токенов для всех веб-служб:
Создание токена:
<?php
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: СЕЙЧАС, давайте защитим файл PHP обработчика ajaxс,
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% повышение безопасности!