php计时器只允许用户每两秒输入一次

我正在编写一个可以发布内容的网站。 这适用于以下jQuery ajax:

$.ajax({ type: 'POST', url: 'action/post.php', data: 'posttext='+posttext+'&imageurl='+imageurl, success: function(feedback){ $('#feedback').val(feedback); } }); 

现在我想知道:任何人都可以编写自己的ajax来向网站发布内容并一遍又一遍地执行此操作。 我该如何防止这种情况? 我确信我需要在post.php中进行某种安全检查 – 我已经听说过http referer,但是这可以修改,所以它不值得信赖。

另外我想在post.php中添加一个计时器,确保来自同一个IP地址的post每x秒只能发布一次,如果post发送到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 '
try again'; 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 (fe 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; }