While the specific programming is beyond the scope of this thread, there are **many** ways to do this. Doing it securely is another matter entirely.
The bottom line is that when someone chooses a name and password, if you are using a scripted user login system, you simply store the user name and password in an encrypted form in a database.
A www authentication scheme is a whole different matter, as this operates on the server system level. This indeed can be done - but it means allowing the script to edit your .htpasswd file. IMO this is a Bad Idea because only root or the direct domain owner should have perms to edit .htaccess or .htpasswd. But it is done, and it is done a lot.
Automatically logging in:
For a scripted system, this is easy. You set a session-only cookie storing the user's login name and the password in encrypted form in the user's browser. Read the cookie first on request, if a user and pass is not found, look for input and read the login input from a form, and if a matching value is found in the database for one or the other, log them into services. If no matching entry is found, return a please log in page.
For www authentication, this is a bit more tricky, and may not evem be possible any more. I can't recall the syntax and I seem to remember something has changed a few years back, but for a while there it was possible to send remote www authentication via a typical query string by doing something like
Which is also a Bad Idea because it requires you pass a plain text password via your query string.