编辑用户登录与退出的php代码
时间: 2024-09-20 09:17:27 浏览: 47
PHP laravel框架开发实践项目代码
在PHP中编辑用户登录和注销功能的基本代码通常涉及以下几个步骤:
**登录(Login.php)**:
```php
<?php
session_start();
// 检查用户是否已经登录
if(isset($_SESSION['username'])) {
header("Location: dashboard.php"); // 如果已登录,重定向到仪表盘页面
} else {
if($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $_POST['username'];
$password = $_POST['password'];
// 连接到数据库(这里仅做示例,实际应用需要连接并验证)
$conn = mysqli_connect("localhost", "db_user", "db_password", "database_name");
$query = "SELECT * FROM users WHERE username = ?";
$stmt = mysqli_prepare($conn, $query);
mysqli_stmt_bind_param($stmt, "s", $username);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
if(mysqli_num_rows($stmt) == 1) {
$row = mysqli_fetch_assoc($stmt);
if(password_verify($password, $row['password'])) {
$_SESSION['username'] = $username;
header("Location: dashboard.php");
} else {
echo "Invalid credentials!";
}
} else {
echo "User not found!";
}
mysqli_stmt_close($stmt);
mysqli_close($conn);
} else {
// 显示登录表单
include 'login_form.html';
}
}
?>
```
**注销(Logout.php)**:
```php
<?php
session_start();
session_unset(); // 清除所有会话变量
session_destroy(); // 销毁当前会话
header("Location: login.php"); // 重定向回登录页
exit; // 确保页面不再执行其他代码
?>
```
**登录表单(login_form.html)**:
```html
<form method="post" action="Login.php">
<label>Username:</label>
<input type="text" name="username" required><br>
<label>Password:</label>
<input type="password" name="password" required><br>
<button type="submit">Login</button>
</form>
```
阅读全文