0

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.

R__
  • 183
  • 2
  • 11
  • 3
    Sidenote: Not only that, but a lot more work using a text file. Any special reason you're not using a database for this? (a lot more manageable too) *Just curious*. – Funk Forty Niner Oct 30 '15 at 18:52
  • @Fred-ii- I'm developing something that'll be transferred from a domain to another regularly, and I can't use a database for that. I encrypt things into text files with keys I change daily. I know it's not very secure, but it's the best I can do. – R__ Oct 30 '15 at 18:59
  • 3
    Have you considered using SQLite? – Mike Oct 30 '15 at 18:59

1 Answers1

1

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.

AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
Amal Murali
  • 75,622
  • 18
  • 128
  • 150