You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP 5.6实现无邮件式后台密码重置(测试Admin面板)

Hey there! Since you're new to PHP and building an admin panel with PHP 5.6, let's tackle the password reset (no email needed) and username update functionality you're after. I'll walk you through each part with code snippets tailored to your users table, and explain the logic so you can follow along easily.

1. First: Display a User List (For Admin to Select Who to Modify)

First, we need a page that shows all users in your database. This gives the admin a way to pick which user's credentials they want to update.

<?php
// Database connection config - update these to your own
$host = 'localhost';
$dbname = 'your_database_name';
$db_user = 'your_db_username';
$db_pass = 'your_db_password';

// Create connection
$conn = new mysqli($host, $db_user, $db_pass, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Fetch all users (we don't need the password here for security)
$sql = "SELECT ID, USERNAME, CREATED FROM users";
$result = $conn->query($sql);
?>

<!DOCTYPE html>
<html>
<head>
    <title>Admin - User Management</title>
    <style>
        table { border-collapse: collapse; width: 80%; margin: 2rem auto; }
        th, td { border: 1px solid #ddd; padding: 0.8rem; text-align: left; }
        th { background: #f2f2f2; }
        .edit-link { background: #4CAF50; color: white; padding: 0.4rem 0.8rem; border-radius: 4px; text-decoration: none; }
    </style>
</head>
<body>
    <h2 style="text-align:center;">User List</h2>
    <?php if ($result->num_rows > 0): ?>
        <table>
            <tr>
                <th>ID</th>
                <th>Username</th>
                <th>Created Date</th>
                <th>Action</th>
            </tr>
            <?php while($row = $result->fetch_assoc()): ?>
            <tr>
                <td><?php echo htmlspecialchars($row["ID"]); ?></td>
                <td><?php echo htmlspecialchars($row["USERNAME"]); ?></td>
                <td><?php echo htmlspecialchars($row["CREATED"]); ?></td>
                <td><a class="edit-link" href="edit-user.php?id=<?php echo htmlspecialchars($row["ID"]); ?>">Edit</a></td>
            </tr>
            <?php endwhile; ?>
        </table>
    <?php else: ?>
        <p style="text-align:center;">No users found.</p>
    <?php endif; ?>
    <?php $conn->close(); ?>
</body>
</html>

Quick Notes:

  • We use htmlspecialchars() to prevent XSS attacks when displaying user data.
  • The "Edit" link passes the user's ID to a separate edit page (edit-user.php).
2. Edit User Form (For Admin to Input New Credentials)

This page loads the selected user's current info and lets the admin input a new username or password (both are optional - leave one blank to skip updating it).

<?php
// Validate the user ID from the URL
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    die("Invalid user ID.");
}
$user_id = $_GET['id'];

// Database connection (same as before)
$host = 'localhost';
$dbname = 'your_database_name';
$db_user = 'your_db_username';
$db_pass = 'your_db_password';

$conn = new mysqli($host, $db_user, $db_pass, $dbname);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Fetch the user's current data using a prepared statement (prevents SQL injection)
$sql = "SELECT ID, USERNAME FROM users WHERE ID = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result();
$user = $result->fetch_assoc();

if (!$user) {
    die("User not found.");
}

$stmt->close();
?>

<!DOCTYPE html>
<html>
<head>
    <title>Admin - Edit User</title>
    <style>
        .form-container { width: 400px; margin: 3rem auto; padding: 1.5rem; border: 1px solid #ddd; border-radius: 8px; }
        .form-group { margin-bottom: 1rem; }
        label { display: block; margin-bottom: 0.5rem; }
        input { width: 100%; padding: 0.6rem; box-sizing: border-box; }
        .submit-btn { background: #4CAF50; color: white; border: none; padding: 0.8rem 1.2rem; border-radius: 4px; cursor: pointer; }
        .submit-btn:hover { background: #45a049; }
    </style>
</head>
<body>
    <div class="form-container">
        <h2>Edit User Details</h2>
        <form method="post" action="update-user.php">
            <!-- Hidden field to pass the user ID -->
            <input type="hidden" name="user_id" value="<?php echo htmlspecialchars($user['ID']); ?>">
            
            <div class="form-group">
                <label>Current Username:</label>
                <input type="text" value="<?php echo htmlspecialchars($user['USERNAME']); ?>" disabled>
            </div>
            
            <div class="form-group">
                <label>New Username (leave blank to keep current):</label>
                <input type="text" name="new_username">
            </div>
            
            <div class="form-group">
                <label>New Password (leave blank to keep current):</label>
                <input type="password" name="new_password">
            </div>
            
            <button type="submit" class="submit-btn">Save Changes</button>
        </form>
    </div>
    <?php $conn->close(); ?>
</body>
</html>

Quick Notes:

  • Prepared statements (prepare() + bind_param()) are used here to avoid SQL injection, since we're using user-provided data (the ID from the URL).
  • The current username is disabled so the admin can't accidentally overwrite it without entering a new one.
3. Process the Update Request

This page handles the form submission, validates the input, and updates the database. We'll hash the password for security (never store plain text passwords!).

<?php
// Only allow POST requests
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    die("Invalid request method.");
}

// Get form data
$user_id = $_POST['user_id'] ?? '';
$new_username = trim($_POST['new_username'] ?? '');
$new_password = trim($_POST['new_password'] ?? '');

// Validate user ID
if (!is_numeric($user_id)) {
    die("Invalid user ID.");
}

// Database connection
$host = 'localhost';
$dbname = 'your_database_name';
$db_user = 'your_db_username';
$db_pass = 'your_db_password';

$conn = new mysqli($host, $db_user, $db_pass, $dbname);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Build the update query dynamically (only update fields that have input)
$update_fields = [];
$params = [];
$param_types = '';

// Add username to update if provided
if (!empty($new_username)) {
    $update_fields[] = "USERNAME = ?";
    $params[] = $new_username;
    $param_types .= "s"; // 's' for string
}

// Add password to update if provided (hash it first!)
if (!empty($new_password)) {
    $hashed_password = password_hash($new_password, PASSWORD_DEFAULT);
    $update_fields[] = "PASSWORD = ?";
    $params[] = $hashed_password;
    $param_types .= "s";
}

// If no fields to update, redirect back to user list
if (empty($update_fields)) {
    header("Location: user-list.php");
    exit;
}

// Add user ID to parameters
$param_types .= "i"; // 'i' for integer
$params[] = $user_id;

// Create and execute the prepared statement
$sql = "UPDATE users SET " . implode(", ", $update_fields) . " WHERE ID = ?";
$stmt = $conn->prepare($sql);

// Bind parameters (use call_user_func_array for variable number of params)
call_user_func_array([$stmt, 'bind_param'], array_merge([$param_types], $params));

if ($stmt->execute()) {
    echo "<p style='text-align:center; margin-top:3rem;'>User details updated successfully! <a href='user-list.php'>Back to User List</a></p>";
} else {
    echo "<p style='text-align:center; margin-top:3rem;'>Update failed: " . $stmt->error . "</p>";
}

$stmt->close();
$conn->close();
?>

Quick Notes:

  • password_hash() is used to securely hash passwords (PHP 5.6 supports this function, which is way safer than MD5/SHA1).
  • We only update fields that have input - if the admin leaves the new username blank, the old one stays, same for password.
Important Security Tips for PHP 5.6

Since PHP 5.6 is no longer receiving security updates, keep these in mind:

  • Always use prepared statements to prevent SQL injection.
  • Never store plain text passwords - stick with password_hash() and password_verify() for login.
  • Add admin authentication - make sure only authorized users can access these pages (e.g., check for a valid admin session).
  • Sanitize all output with htmlspecialchars() to prevent XSS attacks.

内容的提问来源于stack exchange,提问作者david

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 10:01:17