作者:mobiledu2502862117 | 来源:互联网 | 2024-12-14 22:32
为了确保系统的安全性,下面是一个PHP用户认证和管理的完整代码实例。该实例包括了用户认证、数据库连接以及错误处理等多个方面的实现。
认证脚本(auth.inc):
$id = "exampleRealm";
if (!isset($_SERVER['PHP_AUTH_USER'])) {
header('WWW-Authenticate: Basic realm="' . $id . '"');
header('HTTP/1.0 401 Unauthorized');
require('error.inc');
exit;
}
$username = $_SERVER['PHP_AUTH_USER'];
$password = $_SERVER['PHP_AUTH_PW'];
require('database_connection.inc');
$query = "SELECT * FROM users WHERE username='$username' AND realm='$id'";
$result = mysqli_query($connection, $query);
if (mysqli_num_rows($result) == 0) {
header('WWW-Authenticate: Basic realm="' . $id . '"');
header('HTTP/1.0 401 Unauthorized');
require('error.inc');
exit;
}
$isActive = mysqli_fetch_assoc($result)['active'];
if ($isActive == 'no') {
echo "Access DeniedYour account is inactive.
";
exit;
}
?>
数据库连接脚本(database_connection.inc):
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "exampleDB";
$cOnnection= mysqli_connect($servername, $username, $password, $dbname);
if (!$connection) {
die("Connection failed: " . mysqli_connect_error());
}
?>
错误处理脚本(error.inc):
echo "ErrorAuthentication failed. Please try again.
";
?>
用户表结构(users表):
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL UNIQUE,
password VARCHAR(50) NOT NULL,
realm VARCHAR(50) NOT NULL,
active ENUM('yes', 'no') NOT NULL DEFAULT 'no'
);
添加用户示例:
INSERT INTO users (username, password, realm, active) VALUES ('admin', 'hashed_password', 'exampleRealm', 'yes');
用户管理界面(usermanage.php):
include('auth.inc');
if ($_SERVER['PHP_AUTH_USER'] != 'admin' || $_SERVER['PHP_AUTH_PW'] != 'hashed_password') {
header('WWW-Authenticate: Basic realm="exampleRealm"');
header('HTTP/1.0 401 Unauthorized');
echo "Access Denied!";
exit;
}
include('database_connection.inc');
$action = isset($_GET['action']) ? $_GET['action'] : null;
$id = isset($_GET['id']) ? intval($_GET['id']) : 0;
switch ($action) {
case 'activate':
$query = "UPDATE users SET active='yes' WHERE id=$id";
if (mysqli_query($connection, $query)) {
echo "User activated successfully.";
} else {
echo "Error activating user.";
}
break;
case 'deactivate':
$query = "UPDATE users SET active='no' WHERE id=$id";
if (mysqli_query($connection, $query)) {
echo "User deactivated successfully.";
} else {
echo "Error deactivating user.";
}
break;
case 'delete':
$query = "DELETE FROM users WHERE id=$id";
if (mysqli_query($connection, $query)) {
echo "User deleted successfully.";
} else {
echo "Error deleting user.";
}
break;
default:
$query = "SELECT * FROM users";
$result = mysqli_query($connection, $query);
if ($result) {
echo "";
echo "Username | Active | Action |
";
while ($row = mysqli_fetch_assoc($result)) {
$username = $row['username'];
$active = $row['active'];
echo "$username | $active | "; if ($active == 'yes') { echo "Deactivate | "; } else { echo "Activate | "; } echo "Delete |
";
}
echo "
";
}
break;
}
?>