php登录注册修改密码代码
时间: 2024-10-23 22:00:40 浏览: 30
PHP 登录、注册和修改密码的基本流程可以分为以下几个步骤,这里提供一个简化版的示例:
1. **登录系统**:
```php
// 连接数据库
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// 用户提交表单数据
$username = $_POST['username'];
$password = $_POST['password'];
// 验证用户名和密码是否匹配
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows == 1) {
$row = $result->fetch_assoc();
if (password_verify($password, $row['password'])) {
// 登录成功,设置session或其他方式保持用户登录状态
session_start();
$_SESSION['user_id'] = $row['id'];
header("Location: dashboard.php");
} else {
echo "Invalid password.";
}
} else {
echo "User not found.";
}
$stmt->close();
$conn->close();
```
2. **注册系统**:
```php
if ($_SERVER["REQUEST_METHOD"] === "POST") {
// 数据验证
$username = trim($_POST['username']);
// ... (对其他字段进行验证)
$hashed_password = password_hash($_POST['password'], PASSWORD_DEFAULT);
$stmt = $conn->prepare("INSERT INTO users (username, password) VALUES (?, ?)");
$stmt->bind_param("ss", $username, $hashed_password);
$stmt->execute();
$stmt->close();
// 注册成功后跳转到登录页面
header("Location: login.php");
}
```
3. **修改密码**:
```php
if ($_SERVER["REQUEST_METHOD"] === "POST") {
// 获取当前登录用户的ID
session_start();
$userId = $_SESSION['user_id'];
$oldPassword = $_POST['old_password'];
$newPassword = $_POST['new_password'];
// 验证旧密码,然后更新新密码
$stmt = $conn->prepare("SELECT password FROM users WHERE id = ?");
$stmt->bind_param("i", $userId);
$stmt->execute();
$row = $stmt->get_result()->fetch_assoc();
if (password_verify($oldPassword, $row['password'])) {
$hashed_new_password = password_hash($newPassword, PASSWORD_DEFAULT);
$stmt = $conn->prepare("UPDATE users SET password=? WHERE id=?");
$stmt->bind_param("si", $hashed_new_password, $userId);
$stmt->execute();
$stmt->close();
// 密码更改成功,提示用户
echo "Password updated successfully.";
} else {
echo "Old password is incorrect.";
}
}
```
以上代码只是一个基本框架,实际应用中需要添加更多的错误处理和安全性措施,例如防止 SQL 注入、密码强度检查等。
阅读全文
相关推荐


















