php 注册 登录 demo
时间: 2023-07-04 20:20:19 浏览: 36
这是一个简单的 PHP 注册登录示例:
注册页面(register.php):
```php
<!doctype html>
<html>
<head>
<title>用户注册</title>
</head>
<body>
<h1>用户注册</h1>
<form action="register.php" method="post">
<label for="username">用户名:</label>
<input type="text" id="username" name="username" required><br>
<label for="password">密码:</label>
<input type="password" id="password" name="password" required><br>
<input type="submit" value="注册">
</form>
</body>
</html>
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$username = $_POST['username'];
$password = $_POST['password'];
// 将用户名和密码存入数据库
$conn = mysqli_connect('localhost', 'root', 'password', 'database_name');
$sql = "INSERT INTO users (username, password) VALUES ('$username', '$password')";
mysqli_query($conn, $sql);
mysqli_close($conn);
header("Location: login.php"); // 注册成功后跳转到登录页面
}
?>
```
登录页面(login.php):
```php
<!doctype html>
<html>
<head>
<title>用户登录</title>
</head>
<body>
<h1>用户登录</h1>
<form action="login.php" method="post">
<label for="username">用户名:</label>
<input type="text" id="username" name="username" required><br>
<label for="password">密码:</label>
<input type="password" id="password" name="password" required><br>
<input type="submit" value="登录">
</form>
</body>
</html>
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$username = $_POST['username'];
$password = $_POST['password'];
// 在数据库中查找该用户
$conn = mysqli_connect('localhost', 'root', 'password', 'database_name');
$sql = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
mysqli_close($conn);
if ($row) {
session_start();
$_SESSION['username'] = $username; // 将用户名存入 session
header("Location: home.php"); // 登录成功后跳转到首页
} else {
echo "用户名或密码错误";
}
}
?>
```
首页(home.php):
```php
<!doctype html>
<html>
<head>
<title>首页</title>
</head>
<body>
<h1>欢迎 <?php echo $_SESSION['username']; ?> 登录</h1>
<a href="logout.php">退出登录</a>
</body>
</html>
```
退出登录页面(logout.php):
```php
<?php
session_start();
session_destroy(); // 销毁 session
header("Location: login.php"); // 跳转到登录页面
?>
```
注意:上述示例中的数据库连接信息需要根据实际情况进行修改。此外,为了安全起见,密码应该进行加密存储。