PHP PIN登录页面开发:登录后显示"Welcome 用户名"需求及代码求助
实现基于6位PIN码的登录并在欢迎页显示用户名
我来帮你完善这个登录逻辑,同时解决潜在的安全问题,顺利实现登录后在欢迎页显示用户名的功能。首先你的原代码存在SQL注入风险,直接把用户输入的loginid拼接到SQL语句里是非常危险的,我们先把这个问题解决,再补全完整的登录流程:
1. 优化后的登录处理代码
<?php // 必须在任何输出之前开启会话 session_start(); $error = ''; if (isset($_POST['submit'])) { require 'dbconnect_inc.php'; // 使用预处理语句避免SQL注入 $loginid = $_POST['loginid']; // 先验证输入是否是6位数字(符合PIN码格式要求) if (!preg_match('/^\d{6}$/', $loginid)) { $error = '请输入有效的6位数字PIN码'; } else { $stmt = mysqli_prepare($conn, 'SELECT user_first FROM hpnhusers WHERE user_loginid = ?'); mysqli_stmt_bind_param($stmt, 's', $loginid); mysqli_stmt_execute($stmt); $result = mysqli_stmt_get_result($stmt); if ($user = mysqli_fetch_assoc($result)) { // 登录成功,将用户名存入会话 $_SESSION['user_first'] = $user['user_first']; // 跳转到欢迎页,避免表单重复提交 header('Location: welcome.php'); exit(); } else { $error = 'PIN码不正确,请重新输入'; } // 关闭预处理语句和数据库连接 mysqli_stmt_close($stmt); mysqli_close($conn); } } ?> <!-- 你的登录表单HTML部分可以放在这里 --> <form method="post" action=""> <label>6位PIN码:</label> <input type="text" name="loginid" maxlength="6" required> <button type="submit" name="submit">登录</button> <?php if (!empty($error)) echo '<p style="color:red;">' . $error . '</p>'; ?> </form>
2. 欢迎页(welcome.php)代码
<?php session_start(); // 检查用户是否已登录,未登录则跳转回登录页 if (!isset($_SESSION['user_first'])) { header('Location: login.php'); exit(); } ?> <!DOCTYPE html> <html> <head> <title>欢迎页</title> </head> <body> <h1>Welcome <?php echo htmlspecialchars($_SESSION['user_first']); ?></h1> <!-- 可选:添加退出登录功能 --> <form method="post" action="logout.php"> <button type="submit" name="logout">退出登录</button> </form> </body> </html>
3. 可选:退出登录功能(logout.php)
<?php session_start(); // 销毁会话数据 session_unset(); session_destroy(); // 跳转回登录页 header('Location: login.php'); exit(); ?>
关键注意点:
- SQL注入防护:使用mysqli预处理语句和参数绑定,永远不要直接拼接用户输入到SQL语句中
- 会话安全:
session_start()必须放在所有输出(包括HTML空格、换行)之前,否则会触发报错 - 输入验证:添加了6位数字的格式验证,确保用户输入符合PIN码的要求
- XSS防护:在欢迎页使用
htmlspecialchars()输出用户名,避免跨站脚本攻击
内容的提问来源于stack exchange,提问作者user5371085
相关产品推荐
相关产品推荐

