用PHP+MySQL写一个完整的注册登录页面
时间: 2024-05-07 20:20:06 浏览: 6
以下是一个简单的PHP+MySQL注册登录页面的示例代码:
注册页面(register.php):
```php
<?php
// 如果用户已经登录,则重定向到主页
if (isset($_SESSION['user_id'])) {
header('Location: index.php');
exit();
}
// 处理用户提交的注册信息
if (isset($_POST['submit'])) {
// 连接数据库
$conn = mysqli_connect('localhost', 'username', 'password', 'database_name');
// 检查用户名是否已存在
$username = mysqli_real_escape_string($conn, $_POST['username']);
$query = "SELECT * FROM users WHERE username = '$username'";
$result = mysqli_query($conn, $query);
if (mysqli_num_rows($result) > 0) {
$error_message = '该用户名已被注册!';
} else {
// 将新用户插入到数据库中
$password = password_hash($_POST['password'], PASSWORD_DEFAULT);
$query = "INSERT INTO users (username, password) VALUES ('$username', '$password')";
mysqli_query($conn, $query);
$_SESSION['user_id'] = mysqli_insert_id($conn);
header('Location: index.php');
exit();
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>注册</title>
</head>
<body>
<h1>注册</h1>
<?php if (isset($error_message)): ?>
<p><?php echo $error_message; ?></p>
<?php endif; ?>
<form method="post" action="register.php">
<label for="username">用户名:</label>
<input type="text" name="username" id="username" required>
<br>
<label for="password">密码:</label>
<input type="password" name="password" id="password" required>
<br>
<input type="submit" name="submit" value="注册">
</form>
</body>
</html>
```
登录页面(login.php):
```php
<?php
// 如果用户已经登录,则重定向到主页
if (isset($_SESSION['user_id'])) {
header('Location: index.php');
exit();
}
// 处理用户提交的登录信息
if (isset($_POST['submit'])) {
// 连接数据库
$conn = mysqli_connect('localhost', 'username', 'password', 'database_name');
// 检查用户名和密码是否匹配
$username = mysqli_real_escape_string($conn, $_POST['username']);
$query = "SELECT * FROM users WHERE username = '$username'";
$result = mysqli_query($conn, $query);
if (mysqli_num_rows($result) > 0) {
$user = mysqli_fetch_assoc($result);
if (password_verify($_POST['password'], $user['password'])) {
$_SESSION['user_id'] = $user['id'];
header('Location: index.php');
exit();
} else {
$error_message = '密码错误!';
}
} else {
$error_message = '该用户不存在!';
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>登录</title>
</head>
<body>
<h1>登录</h1>
<?php if (isset($error_message)): ?>
<p><?php echo $error_message; ?></p>
<?php endif; ?>
<form method="post" action="login.php">
<label for="username">用户名:</label>
<input type="text" name="username" id="username" required>
<br>
<label for="password">密码:</label>
<input type="password" name="password" id="password" required>
<br>
<input type="submit" name="submit" value="登录">
</form>
</body>
</html>
```
这个示例代码使用了MySQL数据库来存储用户信息。在实际开发中,应该使用加密的连接和预处理语句来避免SQL注入攻击。