<?php $servername = "localhost"; $username = "yourusername"; $password = "yourpassword"; $dbname = "yourdatabase"; // 创建连接 $conn = new mysqli($servername, $username, $password, $dbname); // 检查连接是否成功 if ($conn->connect_error) { die("连接失败: " . $conn->connect_error); } // 获取表单提交的用户名和密码 $username = $_POST['username']; $password = $_POST['password']; // 查询用户表中是否存在该用户 $sql = "SELECT * FROM users WHERE username='$username' AND password='$password'"; $result = $conn->query($sql); // 判断查询结果是否为空 if ($result->num_rows > 0) { echo "登录成功!"; } else { echo "用户名或密码错误!"; } // 关闭连接 $conn->close(); ?> 使用密码哈希加密
时间: 2024-03-24 11:40:32 浏览: 84
好的,下面是使用密码哈希加密的代码,该代码实现了与MySQL数据库的连接和登录验证并使用了密码哈希加密:
HTML登录页面:
```
<!DOCTYPE html>
<html>
<head>
<title>登录页面</title>
</head>
<body>
<h2>登录</h2>
<form method="post" action="login.php">
<label>用户名:</label><input type="text" name="username" required><br>
<label>密码:</label><input type="password" name="password" required><br>
<input type="submit" value="登录">
</form>
</body>
</html>
```
login.php文件:
```
<?php
$servername = "localhost";
$username = "yourusername";
$password = "yourpassword";
$dbname = "yourdatabase";
// 创建连接
$conn = new mysqli($servername, $username, $password, $dbname);
// 检查连接是否成功
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
// 获取表单提交的用户名和密码
$username = $_POST['username'];
$password = $_POST['password'];
// 使用密码哈希加密
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
// 查询用户表中是否存在该用户
$sql = "SELECT * FROM users WHERE username='$username'";
$result = $conn->query($sql);
// 判断查询结果是否为空
if ($result->num_rows > 0) {
// 获取密码哈希
$row = $result->fetch_assoc();
$hashed_password_db = $row['password'];
// 验证密码
if (password_verify($password, $hashed_password_db)) {
echo "登录成功!";
} else {
echo "用户名或密码错误!";
}
} else {
echo "用户名或密码错误!";
}
// 关闭连接
$conn->close();
?>
```
请注意,此处使用了PHP内置的password_hash()和password_verify()函数来实现密码哈希加密和验证。
阅读全文