以下是一个简单的 PHP + MySQL 用户注册登录验证的示例代码:
注册页面(register.php)
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>用户注册</title>
</head>
<body>
<h2>用户注册</h2>
<form action="register.php" method="post">
<label for="username">用户名:</label>
<input type="text" name="username" id="username"><br>
<label for="password">密码:</label>
<input type="password" name="password" id="password"><br>
<label for="confirm_password">确认密码:</label>
<input type="password" name="confirm_password" id="confirm_password"><br>
<input type="submit" value="注册">
</form>
</body>
</html>
```
register.php 处理用户提交的注册信息
```php
<?php
// 连接 MySQL 数据库
$mysqli = new mysqli('localhost', 'root', 'password', 'test');
if ($mysqli->connect_errno) {
echo '连接 MySQL 失败:' . $mysqli->connect_error;
exit();
}
// 处理用户提交的注册信息
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// 获取表单提交的数据
$username = $_POST['username'];
$password = $_POST['password'];
$confirm_password = $_POST['confirm_password'];
// 验证密码是否相等
if ($password !== $confirm_password) {
echo '两次输入的密码不相等';
exit();
}
// 查询用户名是否已经存在
$sql = "SELECT * FROM users WHERE username='$username'";
$result = $mysqli->query($sql);
if ($result->num_rows > 0) {
echo '用户名已经存在';
exit();
}
// 插入新用户数据到数据库
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
$sql = "INSERT INTO users (username, password) VALUES ('$username', '$hashed_password')";
if ($mysqli->query($sql)) {
echo '注册成功';
} else {
echo '注册失败:' . $mysqli->error;
}
}
// 关闭数据库连接
$mysqli->close();
```
登录页面(login.php)
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>用户登录</title>
</head>
<body>
<h2>用户登录</h2>
<form action="login.php" method="post">
<label for="username">用户名:</label>
<input type="text" name="username" id="username"><br>
<label for="password">密码:</label>
<input type="password" name="password" id="password"><br>
<input type="submit" value="登录">
</form>
</body>
</html>
```
login.php 处理用户提交的登录信息
```php
<?php
// 启动会话
session_start();
// 连接 MySQL 数据库
$mysqli = new mysqli('localhost', 'root', 'password', 'test');
if ($mysqli->connect_errno) {
echo '连接 MySQL 失败:' . $mysqli->connect_error;
exit();
}
// 处理用户提交的登录信息
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// 获取表单提交的数据
$username = $_POST['username'];
$password = $_POST['password'];
// 查询用户数据
$sql = "SELECT * FROM users WHERE username='$username'";
$result = $mysqli->query($sql);
if ($result->num_rows > 0) {
$user = $result->fetch_assoc();
// 验证密码是否正确
if (password_verify($password, $user['password'])) {
// 登录成功,保存用户信息到会话
$_SESSION['user_id'] = $user['id'];
$_SESSION['username'] = $user['username'];
echo '登录成功';
} else {
echo '密码错误';
}
} else {
echo '用户名不存在';
}
}
// 关闭数据库连接
$mysqli->close();
```
注销页面(logout.php)
```php
<?php
// 启动会话
session_start();
// 删除保存的用户信息
unset($_SESSION['user_id']);
unset($_SESSION['username']);
echo '注销成功';
```
BC链 http://www.chinabic.com/?id=84 转载需授权!
网友评论