我正在编写一个网站,你可以在其中发布东西。这适用于以下jQuery ajax:
$.ajax({
type: 'POST',
url: 'action/post.php',
data: 'posttext='+posttext+'&imageurl='+imageurl,
success: function(feedback){
$('#feedback').val(feedback);
}
});
现在我想知道:任何人都可以编写自己的ajax来将某些内容发布到网站上,并一遍又一遍地这样做。我该如何防止这种情况?我确定我需要在后期进行某种安全检查.php - 我已经听说过 http referer,但可以修改,所以它并不真正值得信赖。
我还想在 post 中添加一个计时器.php以确保来自同一 IP 地址的帖子只能每 x 秒发布一次,如果帖子发送低于 x 秒,则会重置计时器(有点像堆栈溢出通过评论这样做)。
有谁知道如何保护ajax以及如何设置计时器?或者任何其他想法如何保护发布机制?
谢谢!
丹尼斯
最好的方法是将信息存储在数据库中。 一个表中可以有 4 个字段:
ipAddress, submitDate, postText, imageUrl
提交后,检查数据库中是否有当前 IP 地址的条目。 如果是这样,请将条目的提交日期与当前日期进行比较,如果超过阈值,则允许提交。 否则,发出错误消息并将用户重定向回去。
然而,这仍然不是万无一失的,因为 IP 地址也可能被欺骗,或者用户可能隐藏在代理后面。
只是将IP和请求时间存储在日志文件中。然后检查每个请求上的日志文件是否存在该 IP,并比较存储的时间。
下面是一个简单的脚本,它只允许在 10 秒后来自同一 IP 的请求:
$waitSeconds = 10;
if (allowRequest($waitSeconds)) {
// allowed
echo "Welcome.";
} else {
// not allowed
echo "Please wait at least $waitSeconds after your last request.";
}
echo '<hr /><a href="#" onclick="location.reload(true);return false">try again</a>';
function getLastRequestTimeDiff($ip = null, $logFile = null)
{
if ($ip === null) {
// no specific ip provided, grab vom $_SERVER array
$ip = $_SERVER["REMOTE_ADDR"];
}
if ($logFile === null) {
// no specific log file taken
$logFile = "./lookup.log";
}
if (!is_file($logFile)) {
// touch
file_put_contents($logFile, serialize(array()));
}
// read content
$logContent = file_get_contents($logFile);
// unserialize, check manual
$lookup = unserialize($logContent);
// default diff (f.e. for first request)
$diff = 0;
// current timestamp
$now = time();
if (array_key_exists($ip, $lookup)) {
// we know the ip, retrieve the timestamp and calculate the diff
$diff = $now - $lookup[$ip];
}
// set the new request time
$lookup[$ip] = $now;
// serialize the content
$logContent = serialize($lookup);
// and write it back to our log file
file_put_contents($logFile, $logContent);
// return diff (in seconds)
return $diff;
}
// encapsulate our function in a more simple function (allow yes/no)
function allowRequest($allowed = 10, $ip = null, $logFile = null)
{
$timeDiff = getLastRequestTimeDiff($ip, $logFile);
return $timeDiff >= $allowed;
}