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

usage:

$auth=new HTTP_AUTH;
$auth->passfile="/usr/home/username/password.txt";
$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
{

    var 
$realm;
    var 
$passfile;
    var 
$status;
    var 
$message;

    function 
HTTP_AUTH()
    {
        
$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";
    }

    function 
auth()
    {
        if (!isset(
$_SERVER['PHP_AUTH_USER'])||$_REQUEST['logout']==$_SERVER['PHP_AUTH_USER'])
        {
            
header('WWW-Authenticate: Basic realm="'.$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
            
}
        }
    }
}
?>