PHPMySQL登录验证是一种常见的Web应用程序认证机制,用于验证用户的身份并授权其访问特定的资源或页面。通常,这个过程涉及以下几个步骤:
以下是一个简单的PHPMySQL登录验证示例:
<?php
session_start();
// 连接到MySQL数据库
$servername = "localhost";
$username = "db_user";
$password = "db_password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
// 检查用户输入
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$user = $_POST['username'];
$pass = $_POST['password'];
// 防止SQL注入
$user = $conn->real_escape_string($user);
$pass = $conn->real_escape_string($pass);
// 查询数据库
$sql = "SELECT id FROM users WHERE username='$user' AND password=MD5('$pass')";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// 用户认证成功
$_SESSION['user_id'] = $result->fetch_assoc()['id'];
header("Location: welcome.php");
} else {
echo "用户名或密码错误";
}
}
$conn->close();
?>
<!DOCTYPE html>
<html>
<head>
<title>登录</title>
</head>
<body>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
用户名: <input type="text" name="username"><br>
密码: <input type="password" name="password"><br>
<input type="submit" value="登录">
</form>
</body>
</html>
real_escape_string
或预处理语句(prepared statements)来防止SQL注入攻击。通过以上方法,可以有效地实现PHPMySQL登录验证,并确保系统的安全性和可靠性。
领取专属 10元无门槛券
手把手带您无忧上云