I credit Kevin Yank with Sitepoint for the basic idea here, but this also includes a LOGOUT and a germ of how you could check your usernames and passwords from a database. My hope is that even a newbie could use this script. Note is says what could could be stored as an "include" file (be sure and use require() not include())
<?php
/*
created 2009-09-20 - first use of this
*/
session_start();
//sample logins
$logins=array(
'sfullman'=>'password1',
'jsmith'=>'password2',
'abrown'=>'password3'
);
function login_failure($u,$p){
global $logins;
//fail a blank login (remember password could be '0' so we use strlen())
if(!$u || !strlen($p))return true;
//check session first - this is my system you could use another one
if($_SESSION['systemUserName']==$u && $_SESSION['systemPassword']==$p){
return false;
}
//or you could use a database for this
if($logins[$u]==$p){
$_SESSION['systemUserName']=$u;
$_SESSION['systemPassword']=$p;
return false;
}
return true;
}
//-------------------------------------- begin "include file" --------------------------------
if($logout){
if($_SERVER['PHP_AUTH_USER']==$_SESSION['systemUserName'] && $_SERVER['PHP_AUTH_PW']==$_SESSION['systemPassword']){
unset($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']);
header('WWW-Authenticate: Basic realm="Protected Page: Sign in as another user."');
header('HTTP/1.0 401 Unauthorized');
}
}
if($fail=login_failure($_SERVER['PHP_AUTH_USER'],$_SERVER['PHP_AUTH_PW'])){
// Bad or no username/password.
// Send HTTP 401 error to make the browser prompt the user.
header('WWW-Authenticate: Basic realm="Protected Page: Enter your username and password for access."');
header('HTTP/1.0 401 Unauthorized');
// Display message if user cancels dialog
echo '
<HTML>
<HEAD><TITLE>Authorization Failed</TITLE></HEAD>
<BODY>
<H1>Authorization Failed</H1>
<P>Without a valid username and password,
access to this page cannot be granted.
Please click ‘reload’ and enter a
username and password when prompted.
</P>
</BODY>
</HTML>';
/*
//optional for debugging:
echo '<pre>';
print_r($_SESSION);
print_r($_SERVER);
*/
exit;
}
if($logout){
//optional, redirect to prevent a dialog again if the user refreshes or hits F5..
$q=preg_replace('/&*logout=[01]/','',$GLOBALS['QUERY_STRING']);
if($q)$q='?'.$q;
header('Location: '.$GLOBALS['PHP_SELF'].$q);
exit;
}
//--------------------------- end include file --------------------------
//---------------- page here, we are OK ----------------------
?>
Welcome <?php echo $_SESSION['systemUserName']?><br>
You signed in at <?php echo date('g:iA');?><br>
...page contents here... <br>
<a href="index.php?logout=1">click here to sign out/sign in as another user</a>
<?php
?>