简体   繁体   中英

Removing an unknown part of a string PHP

I'm writing a PHP script that updates a .htpasswd file (yes, I know it's not very secure, but I have several protections to prevent people from accessing the script).

Right now, I'm just appending the current file, like that:

    $user = ''; // (Not an empty strings just removed the part that grabs this for security reasons)
    $password = ''; // (Not an empty strings just removed the part that grabs this for security reasons)
    $password = crypt($password, base64_encode($password));
    $line = $user . ':' . $password;
    $fh = fopen('path/to/password/file','a');
    fwrite($fh,$line);
    fclose($fh);

However, I'd like to remove any current entry on that person. If I knew what their old password was, for example pass123 , I'd just use str_replace($user . ':' . 'pass123','',$currentfiledata) , but I don't, and I have no way to store it.

How would I be able to do this? I assume using preg_replace or something similar, but I'm not experienced with that.

This is not a sane way to perform password updates. But since you already know that, I'm not going to lecture you about the security issues.

If you must do it this way, you can perform the replace using preg_replace() as below:

$currentfiledata = preg_replace('~^'.$user.':.*~m', '', $currentfiledata);

The above statement searches for any line that begins with (asserted by the anchor ^ ) the given username, followed by a colon, and then the password (indicated by .* here - meaning any character, repeated zero or more times). The matches are replaced with an empty string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM