Forum Moderators: coopster

Message Too Old, No Replies

HTTP Authentication with PHP

         

stuartc1

3:58 pm on Oct 14, 2005 (gmt 0)

10+ Year Member



Hi,

Been looking at using PHP to authenticate username/password using HTTP - at first it seemed simple but I came accross a problem with firefox. When users logout using firefox, they can use the back button and refresh to log back in - not ideal. But not the case on IE.

The trick was to use the $_SERVER['HTTP_USER_AGENT'] and if we have MSIE then show the basic logout. For other browsers show a differnt one (the one that doesnt work on IE6+).

Anyone know if this is the best solution?

<?
header("Expires: Sat, 01 Jan 2000 00:00:00 GMT");
header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
header("Cache-Control: post-check=0, pre-check=0",false);
header("Pragma: no-cache");
session_cache_limiter("public, no-store");
session_start();

function auth_user() {
$realm = mt_rand( 1, 1000000000 );
header('WWW-Authenticate: Basic realm="Protected:[ID'.$realm.']"');
header('HTTP/1.0 401 Unauthorized');
die("Unauthorized access forbidden!");
}

if(isset($_GET['logout'])) {
auth_user();
}
if (!isset($_SERVER['PHP_AUTH_USER'])) {
auth_user();
} else if (!isset($_SERVER['PHP_AUTH_PW'])) {
auth_user();
}

mysql_connect("localhost", "root");
mysql_select_db("database_name");
$validate_sql = "SELECT username, password FROM users WHERE username = '".$_SERVER['PHP_AUTH_USER']."' AND password = '".$_SERVER['PHP_AUTH_PW']."'";
if(!$validate_qry = mysql_query($validate_sql)){
die(mysql_error());
}

if(mysql_num_rows($validate_qry) < 1) {
if($_SERVER['PHP_AUTH_USER'] == "logout") {
// message for firefox
die("You have successfully logged out.");
} else {
auth_user();
}
}

echo "You are now logged in <br />";
if (ereg("MSIE", $_SERVER['HTTP_USER_AGENT'])) {
// Use basic logout
echo "<a href=\"".$_SERVER['PHP_SELF']."?logout=y\">Logout</a>";
} else {
// use other logout for Firefox and other browsers
echo "<a href=\"http://logout:logout@".$_SERVER['SERVER_NAME']."/".$_SERVER['PHP_SELF']."\">Logout</a>";
}
?>

cheers

jatar_k

3:48 pm on Oct 17, 2005 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



I have never really had this work very dependably.

When you use standard .htpasswd for auth you can't logout unless you kill the browser.

so I just don't use it. I use standard session stuff for login/logout and it works flawlessly. It gives me more control.