在PHP投票系统中实现防刷票,核心是结合IP限制与Token验证。具体做法:前端生成唯一Token并绑定用户会话,后端校验Token有效性及IP频次,双重验证确保请求合法。

IP频率限制与基础防护
先通过IP地址限制单位时间内的投票次数,防止单一IP频繁提交无效请求。使用Redis存储IP投票计数,设置过期时间控制频率。

IP限制是基础防线,但需警惕代理IP或局域网共享IP导致的误判。建议结合User-Agent和设备指纹增强识别。代码中定义函数check_ip_limit,传入IP和时间窗口,返回是否允许投票。
Token验证机制实现
程序放在app/Services/VoteService.php文件中,运行前确保Redis服务可用。调用vote方法时,系统自动验证Token合法性,成功则记录投票,失败则拒绝。

<?php
namespace App\Services;
use Illuminate\Support\Facades\Redis;
class VoteService
{
private $redis;
public function __construct()
{
$this->redis = Redis::connection();
}
public function vote($userId, $ip, $token)
{
// 验证Token
if (!$this->validateToken($token)) {
return ['success' => false, 'message' => 'Invalid token'];
}
// 检查IP频率
if (!$this->checkIpLimit($ip)) {
return ['success' => false, 'message' => 'Rate limit exceeded'];
}
// 执行投票
$this->recordVote($userId);
return ['success' => true, 'message' => 'Vote recorded'];
}
private function validateToken($token)
{
// 简化示例:实际应验证签名和有效期
return strlen($token) === 32 && ctype_alnum($token);
}
private function checkIpLimit($ip)
{
$key = "vote:ip:" . md5($ip);
$count = $this->redis->get($key);
if ($count && $count >= 10) { // 每小时最多10次
return false;
}
$this->redis->incr($key);
$this->redis->expire($key, 3600); // 1小时过期
return true;
}
private function recordVote($userId)
{
$this->redis->incr("vote:user:" . $userId);
}
}
程序输出为JSON响应,成功时显示'Vote recorded',失败时提示错误原因。输入变化如更换IP或Token无效将触发相应限制。排错时检查Redis连接状态和Token生成逻辑。
Token由前端生成后随请求发送,后端校验其签名和时效性。此机制防止重放攻击和伪造请求。结合IP限制,形成完整防护链。
同一程序中的并发处理问题
直接回答:在高并发场景下,需使用Redis原子操作确保投票计数准确,避免超卖或重复计数。
沿用上述程序,当多个请求同时到达时,Redis的INCR命令保证线程安全。若发现计数异常,检查是否未启用事务或锁机制。优化后可支撑每秒数千次投票请求。