Justtechjobs.com Find a programming school near you






Online Campus Both


php3-list | 199903

Re: [PHP3] .htpasswd From: Cameron Just (ccjust <email protected>)
Date: 03/04/99

Heres some code we just wrote which adds users to a htpasswd file.

1. Creates a temp file called $htpasswdfile.".lock"
2. If this file exists then it waits until doesn't(This stops the
occurrence of two people adding at once)
3. It reads in an existing htpasswd file and dumps contents into and array.
4. Makes sure the new username doesn't already exist.(If it does removes
lock file and exits.)
5. Generates the new username password combination and tacks it onto the end.
6. Writes the new htpasswd file.
7. Removes Lock file.

The Lock file never gets written to it's just there to let other processes
know that the htpasswd file is currently being modified.
This could be done using semaphores but we didn't want to re-learn them
just yet :)
You could also write other functions to delete and modify users using the
same principles.

VARIABLES USED
.............................
$username
$password
$htpasswdfile
............................

function useradd($username,$password) {
global $htpasswdfile;

          while (file_exists($htpasswdfile.".lock")) {
                sleep(1);
                clearstatcache();
          }
        
        symlink($htpasswdfile,$htpasswdfile.".lock");
        $userfile = file($htpasswdfile);
        
        for ($i=0;$i<count($userfile);$i++) {
                $uppairs[] = explode(":",$userfile[$i]);
                $uppairs[$i][1] = trim($uppairs[$i][1]);
                if ($uppairs[$i][0] == $username) {
                        unlink($htpasswdfile.".lock");
                        return -1;
                }
        }
        $uoutfile .= $username.":".crypt($password)."\n";
        
        $ufp = fopen($htpasswdfile,"a");
        fputs($ufp,$uoutfile);
        fclose($ufp);
        unlink($htpasswdfile.".lock");
}
********************************************************************
Cameron Just
Web Development ( Information Technology Services )
University of Queensland
Ph 3365 7412
********************************************************************

--
PHP 3 Mailing List   http://www.php.net/
To unsubscribe send an empty message to php3-unsubscribe <email protected>
To subscribe to the digest list:  php3-digest-subscribe <email protected>
For help: php3-help <email protected>  Archive:  http://www.php.net/mailsearch.php3
List administrator:  zeev-list-admin <email protected>