How can users be allowed to change their passwords in a PHP system encrypted with htpasswd?

To allow users to change their passwords in a PHP system encrypted with htpasswd, you can create a form where users can input their current password and new password. Upon submission, you can verify the current password, re-encrypt the new password, and update the htpasswd file with the new encrypted password for the user.

<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $htpasswd_file = '/path/to/.htpasswd';
    $username = 'user1';
    $current_password = $_POST['current_password'];
    $new_password = $_POST['new_password'];

    $htpasswd_content = file_get_contents($htpasswd_file);
    $htpasswd_lines = explode("\n", $htpasswd_content);

    foreach ($htpasswd_lines as $key => $line) {
        if (strpos($line, $username . ':') === 0) {
            $current_hash = explode(':', $line)[1];
            if (password_verify($current_password, $current_hash)) {
                $new_hash = password_hash($new_password, PASSWORD_DEFAULT);
                $htpasswd_lines[$key] = $username . ':' . $new_hash;
                file_put_contents($htpasswd_file, implode("\n", $htpasswd_lines));
                echo 'Password updated successfully.';
                break;
            } else {
                echo 'Current password is incorrect.';
                break;
            }
        }
    }
}
?>

<form method="post">
    <label for="current_password">Current Password</label>
    <input type="password" id="current_password" name="current_password" required><br>
    
    <label for="new_password">New Password</label>
    <input type="password" id="new_password" name="new_password" required><br>
    
    <input type="submit" value="Change Password">
</form>