php实现扫码登录
实现扫码登录的基本流程
扫码登录的核心流程分为两部分:前端生成二维码并轮询状态,后端验证扫码并返回登录状态。以下是具体实现方法:
生成唯一二维码标识
使用PHP生成一个唯一的token作为二维码内容,通常结合时间戳和随机字符串:
$token = md5(uniqid(mt_rand(), true));
// 存储到数据库或缓存中,设置有效期
$_SESSION['scan_token'] = $token;
建议使用Redis存储token和状态信息,设置过期时间(如300秒)。
前端展示与轮询逻辑
前端通过JavaScript生成二维码并定期检查登录状态:
// 使用qrcode.js生成二维码
new QRCode(document.getElementById("qrcode"), {
text: "https://yourdomain.com/scan?token=<?php echo $token; ?>",
width: 200,
height: 200
});
// 轮询检查状态
setInterval(function() {
fetch('/check_login.php?token=<?php echo $token; ?>')
.then(response => response.json())
.then(data => {
if(data.status === 'confirmed') {
window.location.href = '/user/dashboard';
}
});
}, 2000);
后端验证逻辑
创建check_login.php处理验证请求:
$token = $_GET['token'];
$status = redis_get('scan_status_' . $token);
if ($status === 'confirmed') {
$userId = redis_get('user_id_' . $token);
$_SESSION['user_id'] = $userId;
echo json_encode(['status' => 'confirmed']);
} else {
echo json_encode(['status' => $status ?: 'waiting']);
}
移动端扫码处理
移动端应用扫描二维码后,应调用API通知服务器:

// mobile_api.php
$token = $_POST['token'];
$userId = get_current_user_id(); // 移动端已登录用户
redis_set('scan_status_' . $token, 'confirmed');
redis_set('user_id_' . $token, $userId);
安全增强措施
- 每次token验证后立即失效
- 限制同一IP的频繁请求
- 使用HTTPS保证传输安全
- 添加日志记录扫码行为
if(redis_get('request_count_' . $ip) > 10) {
http_response_code(429);
exit;
}
完整示例代码结构
/scancode
├── generate.php # 生成token和二维码
├── check_login.php # 轮询接口
├── mobile_api.php # 移动端确认接口
└── qrcode.js # 前端生成库
通过以上步骤可实现基础的扫码登录功能,实际部署时需根据具体业务需求调整验证逻辑和安全策略。






