How to write a function to change the passwords of multiple users in PHP

PHPz
Release: 2023-04-04 15:24:01
Original
419 people have browsed it

PHP is a widely used server-side scripting language for developing dynamic websites and web applications. In web applications, it is usually necessary to manage multiple users, including user login, registration, information editing, etc. One common operation is to change the passwords of multiple users. This article will introduce how to use PHP to write a function that changes the passwords of multiple users.

1. Database design

Before writing, we need to design the database structure first. Assume that our system contains a user table named "users", which contains the following fields:

  • id: User ID, self-increasing.
  • username: username.
  • password: Password.
  • email: Email address.
  • role: User role, used to control user permissions in the system.

2. Create a password change form

Create a password change form in HTML. The form includes the following input boxes:

  • Old password: used to verify user identity.
  • New Password: Used to set a new password.
  • Confirm password: Used to confirm the new password again.

The following is a sample HTML code:

<form action="update_password.php" method="post">
    <label for="old_password">旧密码:</label>
    <input type="password" name="old_password">
    <br>
    <label for="new_password">新密码:</label>
    <input type="password" name="new_password">
    <br>
    <label for="confirm_password">确认密码:</label>
    <input type="password" name="confirm_password">
    <br>
    <button type="submit">修改密码</button>
</form>
Copy after login

3. Process the password change request

Next, we have to write a PHP script to handle the password change request. First, get the data submitted by the form:

$old_password = $_POST['old_password'];
$new_password = $_POST['new_password'];
$confirm_password = $_POST['confirm_password'];
Copy after login

Then, verify the validity of the input data:

// 判断新密码和确认密码是否一致
if ($new_password != $confirm_password) {
    die("新密码和确认密码不一致。");
}

// 验证旧密码是否正确
// 假设当前用户ID为1
$user = getUserById(1);
if (!password_verify($old_password, $user['password'])) {
    die("旧密码不正确。");
}
Copy after login

Next, iterate through all users, change the password, and store the results in the array:

$results = array();
$users = getAllUsers();
foreach ($users as $user) {
    // 修改密码
    $new_hashed_password = password_hash($new_password, PASSWORD_DEFAULT);
    $sql = "UPDATE users SET password = '$new_hashed_password' WHERE id = " . $user['id'];
    $result = mysqli_query($conn, $sql);
    if (!$result) {
        // 修改失败
        $results[] = array(
            'user_id' => $user['id'],
            'username' => $user['username'],
            'success' => false
        );
    } else {
        // 修改成功
        $results[] = array(
            'user_id' => $user['id'],
            'username' => $user['username'],
            'success' => true
        );
    }
}
Copy after login

Finally, return the modification result to the user:

foreach ($results as $result) {
    if ($result['success']) {
        echo "用户 " . $result['username'] . " 的密码已成功修改。<br>";
    } else {
        echo "用户 " . $result['username'] . " 的密码修改失败。<br>";
    }
}
Copy after login

4. Complete code

The following is the complete PHP code for modifying multi-user passwords:

<?php
// 数据库连接
$conn = mysqli_connect(&#39;localhost&#39;, &#39;username&#39;, &#39;password&#39;, &#39;database&#39;);

// 获取当前用户信息
function getUserById($user_id) {
    global $conn;
    $sql = "SELECT * FROM users WHERE id = $user_id";
    $result = mysqli_query($conn, $sql);
    $user = mysqli_fetch_assoc($result);
    return $user;
}

// 获取所有用户
function getAllUsers() {
    global $conn;
    $sql = "SELECT * FROM users";
    $result = mysqli_query($conn, $sql);
    $users = mysqli_fetch_all($result, MYSQLI_ASSOC);
    return $users;
}

// 修改密码
function updatePassword($old_password, $new_password, $confirm_password) {
    global $conn;

    // 判断新密码和确认密码是否一致
    if ($new_password != $confirm_password) {
        die("新密码和确认密码不一致。");
    }

    // 验证旧密码是否正确
    // 假设当前用户ID为1
    $user = getUserById(1);
    if (!password_verify($old_password, $user[&#39;password&#39;])) {
        die("旧密码不正确。");
    }

    $results = array();
    $users = getAllUsers();
    foreach ($users as $user) {
        // 修改密码
        $new_hashed_password = password_hash($new_password, PASSWORD_DEFAULT);
        $sql = "UPDATE users SET password = &#39;$new_hashed_password&#39; WHERE id = " . $user[&#39;id&#39;];
        $result = mysqli_query($conn, $sql);
        if (!$result) {
            // 修改失败
            $results[] = array(
                &#39;user_id&#39; => $user['id'],
                'username' => $user['username'],
                'success' => false
            );
        } else {
            // 修改成功
            $results[] = array(
                'user_id' => $user['id'],
                'username' => $user['username'],
                'success' => true
            );
        }
    }

    foreach ($results as $result) {
        if ($result['success']) {
            echo "用户 " . $result['username'] . " 的密码已成功修改。<br>";
        } else {
            echo "用户 " . $result['username'] . " 的密码修改失败。<br>";
        }
    }
}

// 处理表单提交
if (isset($_POST['old_password']) && isset($_POST['new_password']) && isset($_POST['confirm_password'])) {
    updatePassword($_POST['old_password'], $_POST['new_password'], $_POST['confirm_password']);
}
?>
Copy after login

5. Summary

PHP is a powerful server-side scripting language suitable for the development of various web applications. This article introduces how to use PHP to write a function that changes the passwords of multiple users. This function involves database connection, user authentication, data traversal and result output, etc. It has certain challenges for PHP beginners, but mastering the knowledge can provide a foundation for the next step of development.

The above is the detailed content of How to write a function to change the passwords of multiple users in PHP. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!