Web Hosting Talk







View Full Version : PHP/MySQL Authentication


Zing
11-17-2002, 05:12 PM
Hi, I was wondering if anyone could help me with a simple php script which uses the following headers to generate the login box:

header('WWW-Authenticate: Basic realm="My Private Stuff"');
header('HTTP/1.0 401 Unauthorized');
echo 'Authorization Required.';
exit;

Then Authenticates against the main mysql user database, so if user jondoe was setup with a pass in mysql it would also function for this script (obviously script would need root mysql privs, not a problem).

I tried including the PHPMyAdmin scripts but those screw up the way my script works and i'm pretty sure it'd only take a few select statements to do, problem is i've only done it where id is either over 1 then if there's no id found it wouldn't authenticate, but mysql user db has no id column.

If anyone could create a few lines of code to authenticate against the main mysql user table this would be awesome. just echo something for "authorised" "not authorised - you smell" ;)

Best Regards

MarkIL
11-17-2002, 11:20 PM
/* assume DB_USER, DB_PASS are set */
function IsAuthorized($username='',$password='')
{
if (!strlen($username) || !strlen($password)) return false;
$db = @mysql_connect("localhost",DB_USER,DB_PASS);
if (!$db) return false;

mysql_select_db("User", $db);
$q = "SELECT User FROM user WHERE User='%s' AND Password=PASSWORD('%s')";
$r = mysql_query(sprintf($q,escapeshellcmd($username),escapeshellcmd($password)),$db);
$r = mysql_fetch_assoc($r);
if (isset($r['User']) && $r['User']==$username) return true;

return false;
}