Zend - The PHP Company




Authentication

Add Code


complete authentication in one file.  

Type: code fragment
Added by: joeldg
Entered: 15/10/2002
Last modified: 31/10/2001
Rating: **** (3 votes)
Views: 17125
complete auth system in one file. Just include this file, after you have modified the definitions, in any pages you want protected and authentication will be enabled.


<?
/*
complete auth system in one file.
just include this file after you have modified the definitions and authentication will be enabled.

Joel De Gan
http://www.tenshimedia.com
http://www.joihost.com

*/

define("REDIRECT",1); #redir to page, 0 = show form from here
define("USEMYSQL",1); #0=no,1=yes 
define("USEFILE",0); #0=no,1=yes
define("FILEPATH","~.users"); #0=no,1=yes
define("USE_ENCRYPTION",0); #0=no,1=yes
define("VAR_TYPE","session"); # session/cookie
#define("VAR_TYPE","cookie");
define("SHOW_TOP_BAR",1);

#######

define("SHOW_LOGIN_FORM","
    <br><br><center><form method=post action=
$PHP_SELF?show=login></td><table>
    <tr>
        <td>Username: </td>
        <td><input name=username type=text value=></td>
        </tr><tr>
        <td>Password: </td>
        <td><input name=password type=password value=></td>
        </tr><tr>
        <td colspan=2 align=center><input type=submit value="  
log in   "></td>        
    </tr>
    </table>
    </form></center>
"
); #show login form
define("REDIRECT_AFTER_LOGIN","$PHP_SELF"); #redirect to after login
define("FAILED_LOGIN","
    <br><br><center><h2>Login failed - <a href="
$PHP_SELF?show=form">go back</a></h2></center><br><br>
"
); #failed login page
define("LOGOUT","$PHP_SELF?logout=true"); #logout page

define("LOGIN_MYSQL_HOST""localhost");
define("LOGIN_MYSQL_USER""username");
define("LOGIN_MYSQL_PASS""password");
define("LOGIN_MYSQL_DB""any_database");
define("LOGIN_MYSQL_TABLE""usertable");
define("LOGIN_MYSQL_USERFIELD""name"); // whatever field you use for username
define("LOGIN_MYSQL_PASSFIELD""pass"); // whatever field you use for password
define("ADMIN_FIELD","userlevel"); // this is for determining if admin or not
define("ADMIN_FIELD_VALUE","admin"); // the value that determines if admin or not

define ("DB_ERROR_PAGE""<h3>Cannot connect to the database server.</h3>n");
define ("DB_ERROR""<h3>Cannot connect to the database selected.</h3>n");

define("DEBUG","true"); // true=debug; false=no

// loginDatabaseConnect(LOGIN_MYSQL_HOST,LOGIN_MYSQL_USER,LOGIN_MYSQL_PASS,LOGIN_MYSQL_DB);
function loginDatabaseConnect($host$user$pass$db) {
    if (!(
$mylink mysql_connect($host$user$pass))){
            print  
DB_ERROR_PAGE;
        print 
mysql_error();
            exit;
        }
//fi
        
mysql_select_db($db) or die(DB_ERROR mysql_error());
}
// end function

function object_to_cookie($obj){
    
$z serialize($obj);
    
$z gzcompress($z);
    
$z base64_encode($z);
    
$z urlencode($z);
  return 
$z;
}

function 
cookie_to_object($cookie){
    
$z urldecode($cookie);
    
$z base64_decode($z);
    
$z gzuncompress($z);
    
$z unserialize($z);
  return 
$z;


function 
array2cookie($arr){
    while (list(
$key$val)= each($arr)){
        
sec_setcookie($key$val);
        
$key $val;
        global ${
$key};
    }
//rof
}//end function

//main cookie function
function sec_setcookie($var$val$modify=3600){
    if (
USE_ENCRYPTION == 1){ $val object_to_cookie($val); }
    
$exp gmstrftime("%A, %d-%b-%Y %H:%M:%S"time()+$modify);
    
$dom $GLOBALS["HTTP_HOST"];
    if (
preg_match("/^(.*):(.*)$/",$dom,$arr)) {
        
print_r($arr);
        
$dom $arr[1];
    }
    
$parts explode(".",$dom);
    
$dom ".".$parts[count($parts)-2].".".$parts[count($parts)-1];
    
setcookie($var,$valtime()+$modify,"/",$dom0);
    ${
$var} = $val;
    global ${
$var};
}
//end function

function check_login(){
    if ( (isset(
$_COOKIE["loggedin"])&&isset($_COOKIE["username"])&&isset($_COOKIE["password"])) || $loggedin){
        return 
true;
    }else{
          if (!
headers_sent()){
            
# for if we want to redirect instead...
            //header("Location: ". SHOW_LOGIN_FORM);
            //echo SHOW_LOGIN_FORM;
            
header("Location: http://www.yoursite.com/login.php");
            
//exit;
        
}else{
            
//echo "n<br><br><center><a href='".SHOW_LOGIN_FORM."'>CLICK HERE</a> to login</a></center><br><br>n";
            //echo SHOW_LOGIN_FORM;
            
header("Location: http://www.yoursite.com/login.php");

            
//exit;
        
}//fi        
    
}//fi
}//end function


function do_login($username$password){
    if (
USE_ENCRYPTION == 1){ 
        
$password cookie_to_object($password); 
    }
//fi
    
loginDatabaseConnect(LOGIN_MYSQL_HOSTLOGIN_MYSQL_USERLOGIN_MYSQL_PASSLOGIN_MYSQL_DB);
             
$sql "SELECT * FROM "LOGIN_MYSQL_TABLE
             
." WHERE "LOGIN_MYSQL_USERFIELD ."='".$username
             
."' AND "LOGIN_MYSQL_PASSFIELD ."='".$password."'";
        
$tmp mysql_query($sql)or die(DB_ERROR mysql_error());
        if ( 
mysql_num_rows($tmp)>){
            if (
USE_ENCRYPTION == 1){ $password object_to_cookie($password); }
            
sec_setcookie("username"$username);
            
sec_setcookie("password"$password);
            
sec_setcookie("loggedin""true");
            
$row mysql_fetch_array($tmp);
            if (
$row[ADMIN_FIELD] == ADMIN_FIELD_VALUE){
                
sec_setcookie("admin""true");
            }
//fi
            
header("Location: "REDIRECT_AFTER_LOGIN);
            exit;
        }else{
            
sec_setcookie("username""");
            
sec_setcookie("password""");
            
sec_setcookie("loggedin""");
            echo 
FAILED_LOGIN;
            
//header("Location: http://www.yoursite.com/login.php")
            
exit;
            
        }
//fi
}//end function

function show_logout(){
    return 
"<a href="".LOGOUT."">logout</a>";
}
//end function

############################################################################################
###########               below runs each time this file is accessed             ###########
############################################################################################
if ($p <> "signup"){
switch (
$show){
    case 
"login":
        
do_login($HTTP_POST_VARS["username"], $HTTP_POST_VARS["password"]);
        
check_login();
        break;
    case 
"form":
        
check_login();
        break;
    default:
        
check_login();
        break;
}
//switch
}//fi
###########
#echo "test";
if ($HTTP_POST_VARS["logout"] <> "" || $HTTP_GET_VARS["logout"] <> ""){
    while(list(
$key$val) = each($_COOKIE)){
        
sec_setcookie($key"");
    }
//wend
    //header("Location: ". REDIRECT_AFTER_LOGIN);
    
header("Location: http://www.yoursite.com/login.php");
}
//
############################################################################################

if (SHOW_TOP_BAR == && _disptop <> false){
?><body leftmargin="0" topmargin="0" marginwidth="0" marginheight="0">
<table width="100%" border="0" cellspacing="0" cellpadding="0" bgcolor="#000000">
  <tr>
    <td width"100%" bgcolor="#000000" align="right">
    [ <span class=h2>Currently Logged in as:</span> <span class=highlit><? echo $username ?></span>
    | <? echo show_logout(); ?> ] </span> 
    </td>

  </tr>
</table>
<?
}//end function

?>


Usage Example




Rate This Script





Search



This Category All Categories