0

So I've created a directory that I have protected with htaccess. The issue is that I want every user in an SQL table with the 'admin' usertype to be able to use their custom login info. I've set up everything so that the usernames and encrypted passwords should be written to the .htpasswd file (right now I have to run a php script manually to do so, but in the future I'll have the process automated). The issue is that my script doesn't seem to recognize my .htpasswd file as existing. I tried moving the file out of the password protected directory (and changing all references accordingly), but it still won't register the existence of the file.

I'm not sure if this is because I've done something wrong or if php simply can't write to .htpasswd files, or anything in between. Anyway, I'm fairly new to php in the grand scheme of things, and I couldn't find any help just by searching through docs and other forum posts, so I turned to Stack Overflow.

My Code:

//$password is already encrypted
if (!file_exists('/path/to/.htpasswd')) {
            die('File does not exist');
        } else {
            $myfile = fopen('/path/to/.htpasswd') or die('There was a problem opening this file');
            $string = file_get_contents('/path/to/.htpasswd') or die('There was a problem getting the contents of this file');
            $string = explode("\n", $string);
            if (in_array($username.":".$password, $string)) {
                die('User already in .htpasswd file.');
            } else {
                fwrite($myfile, $username.":".$password."\n");
                echo('Added user and password to file.');
            }
        }

Any help is greatly appreciated.

Sam
  • 295
  • 4
  • 17
  • 1
    make sure the user php is running under has write permission to the file. When it's ran by Cron you can run it as any user you want, permissions wont be an issue then. – ArtisticPhoenix Sep 09 '18 at 20:23
  • @ArtisticPhoenix thanks, I've set up a Cron job for it but it returns the same thing. – Sam Sep 09 '18 at 21:31
  • You still have to make sure the user that PHP runs as has permissions, Cron generally runs as the user that created it you can change it with `contab -e -u {user}` as long as you have permission to be that user. If you do it in C-Panel, then it's generally the cPanel user who is PHP. – ArtisticPhoenix Sep 09 '18 at 21:51
  • @ArtisticPhoenix ah, thanks again. I added the read and write permissions to the user, but it still doesn't recognize the file's existence. I may have found a much easier way to connect MySQL and the htaccess apache stuff, so I'll see if that works instead. – Sam Sep 11 '18 at 18:35

0 Answers0