<?php
// Define database constants
define('AUTH_HOST', 'localhost');
define('AUTH_USER', 'WebAuth');
define('AUTH_PASS', 'AuthPass');
define('AUTH_DB', 'WebAuth');
function attempt_auth()
{
// Send authentication headers
header('WWW-Authenticate: Basic realm="Protected by PHP"');
header('HTTP/1.0 401 Unauthorized');
}
function check_login($username, $password)
{
$ret = false;
if ($username && $password)
{
// Check if login matches database values
$conn = mysql_connect(AUTH_HOST, AUTH_USER, AUTH_PASS);
if (mysql_select_db(AUTH_DB, $conn))
{
// Search for matches
$result =
mysql_query("SELECT COUNT(username) AS ucount
FROM Users
WHERE username='" . addslashes($username) . "'
AND passwd_md5='" . md5($password) . "'
AND passwd_sha1='" . sha1($password) . "'",
$conn);
// Check if a match was found
if (($row = mysql_fetch_array($result)) && $row['ucount'])
{
$ret = true;
$_SESSION['username'] = $username;
}
}
// Close connection
mysql_close($conn);
}
return $ret;
}
session_start();
// Check if using valid credentials
if (!(isset($_SESSION['username']) ||
(isset($_SERVER['PHP_AUTH_USER']) &&
check_login($_SERVER['PHP_AUTH_USER'],
$_SERVER['PHP_AUTH_PW']))))
{
// Show login prompt
attempt_auth();
echo 'Authorization Required';
exit;
}
?>