It's an Apache feature - read the Apache docs for more info.
Basically, you need a htpasswd file. These are normally maintained by the "htpasswd" program shipped with Apache.
But the format is simple, you can write it by PHP.
The Apache config (httpd.conf or .htaccess) indicates where the server should find htpasswd, and which user(s) it should allow to access a given resource (being a directory, file or location).
The simplest way to do it, in my opinion, is to have a fixed .htaccess file which doesn't change, then make a htpasswd file somewhere which is writeable by PHP and dynamically updated as new users are added/removed, or change their passwords.
Ensure that the htpasswd file itself is somewhere inaccessible by the web - either ourside the web root or in a special directory protected by a .htaccess such as
Deny From All
Try it out on your dev server first, to see how the Apache basic auth config works.
Mark