<?php
/*
a simple HTTP authentication class
Author: slave@codegrunt.com / http://codegrunt.com

usage:

$args=array(
'realm'=>'private access',
'passfile'=>'/usr/home/foobar/passfile.txt',
'message'=>'This is a private area - members only!'
);

$auth=new HTTP_AUTH($args);
$auth->auth();

script execution will end unless user is authenticated
password file is standard format of username:password where password is an MD5 hash created with "crypt"

*/

class HTTP_AUTH
{

    public 
$realm;
    public 
$passfile;
    public 
$status;
    public 
$message;

    
// optionall take array of arguments to populate attributes
    
function __construct($args=NULL)
    {
        
$this->realm='private area';
        
$this->passfile='/dev/null';
        
$this->status=array('status'=>0); // unauthenticated
        
$this->message="Sorry, you must be authenticated to access this area.\n";

        if(
is_array($args))
        {
            foreach(
$args AS $col=>$val)
            {
                
$this->{$col}=$val;
            }
        }
    }

    function 
auth()
    {
        if (!isset(
$_SERVER['PHP_AUTH_USER'])||$_REQUEST['logout']==$_SERVER['PHP_AUTH_USER'])
        {
            
header('WWW-Authenticate: Basic realm="'.htmlentities($this->realm).'"');
            
header('HTTP/1.0 401 Unauthorized');
            echo 
$this->message;
            exit;
        }
        else
        {
            
// check against password file
            
if($fp=fopen($this->passfile,'r'))
            {
                while(!
feof($fp))
                {
                    
$line=fgets($fp,1024);
                    
$u=explode(':',$line);
                    
$u[1]=trim($u[1]);
                    if(
$u[0]===$_SERVER['PHP_AUTH_USER']&&strlen($_SERVER['PHP_AUTH_USER'])>0)
                    {
                        
$salt=substr($u[1],0,2);
                        if(
crypt($_SERVER['PHP_AUTH_PW'],$salt)===$u[1])
                        {
                            
$this->status['user']=$_SERVER['PHP_AUTH_USER'];
                            
$this->status['status']=1;
                            break;
                        }
                        
/*
                        // uncomment to debug
                        else
                        {
                            $this->message.='<br>'.crypt($_SERVER['PHP_AUTH_PW'],$salt).'='.$u[1];
                            $this->message.='<br>'.strlen(crypt($_SERVER['PHP_AUTH_PW'],$salt)).'='.strlen($u[1]);
                        }
                        */
                    
}
                }
                
fclose($fp);
            }
            else
            {
                
// uncomment to debug
                // $this->message='could not open passfile';
            
}
            if(
$this->status['status']<1)
            {
                unset(
$_SERVER['PHP_AUTH_USER']);
                
$this->auth(); // trigger password request again
            
}
        }
    }
}
?>