我创建了一个具有正常运行登录系统的网站,在我的数据库中的用户表中,有一个标准或管理员的列名称类型。我已经为管理员创建了一个页面,仅用于编辑产品等,但是我无法设置它,因此只有"管理员"才能查看该页面,而不仅仅是登录的任何人。这是我到目前为止所拥有的?
管理员.php
<?session_start(); ?>
<?php
include 'login.php'; // this includes all my login form and login action
include 'connection.php'; // this is my database connection
$query1 = "SELECT type FROM users";
$result = mysqli_query($query1);
$user = mysqli_fetch_array($result);
$_SESSION['usertype'] = $user['usertype'];
if($_SESSION['type'] = 'admin'){
//admin content here
{
<?php
if ($_SESSION['type']) = 'standard')
{
echo 'you must be an admin to see this page';
}
?>
登录操作.php
<?php
session_start();
include'connection.php';
$email = trim($_POST["email"]);
$password = trim($_POST["password"]);
$password=md5($_POST["password"]);
if (empty($email) or empty($password)) {
header("Location: homepage.php?form=invalid"); //Redirection information
exit;
}
if(!filter_var($email, FILTER_VALIDATE_EMAIL))
{
echo "E-mail is not valid";
header("Location: homepage.php?email=invalid");
exit;
}
$query = "SELECT * FROM users WHERE email= '$email' AND password = '$password' ";
$result = mysqli_query($connection, $query) or exit("Error in query: $query. " . mysqli_error());
if ($row = mysqli_fetch_assoc($result)) {//Then we have a successful login
$_SESSION["authenticatedUserEmail"] = $email;
$_SESSION['ID'] = $row['ID'];
$_SESSION["password"] = $row['password'];
header("Location: homepage.php");
} else {//Login was unsuccessful
echo "User does not exist";
header("Location: login.php?user=invalid");
}
?>
您没有使用 comaprison,而是在检查用户类型的条件下为变量设置值。
if($_SESSION['type'] ='admin'){ `should be` if($_SESSION['type'] == 'admin'){
<? session_start(); ?>
<? php
include 'login.php'; // this includes all my login form and login action
include 'connection.php'; // this is my database connection
$query1 = "SELECT type FROM users";
$result = mysqli_query($query1);
$user = mysqli_fetch_array($result);
$_SESSION['usertype'] = $user['usertype'];
if ($_SESSION['type'] == 'admin') {
//admin content here
}
if ($_SESSION['type']) == 'standard') {
echo 'you must be an admin to see this page';
} ?>
代码中还有其他错误,例如未正确使用大括号来结束语句。这段代码应该可以工作,但是这是一个非常不安全的代码,因为任何具有SQL注入和良好编程知识的人都会"撕裂"您的网站,更糟糕的是,他们会窃取和操纵您的数据。
您应该使用 mysql_real_escape_string() 使用户的输入能够在一定程度上证明 sql 注入。
您的代码中也出现了多个问题,以及@Vish在答案中提到的问题:
$result = mysqli_query($query1);
预期连接链接作为第一个参数。
再:
您正在尝试从user table
获取type
。但是在mysqli_fetch_array
中使用usertype
.似乎不正确。$_SESSION['type']
变量真的很$_SESSION['usertype']
?
修改后的代码。
$query1 = "SELECT type FROM users";
$result = mysqli_query($connection, $query1);
$user = mysqli_fetch_array($result);
$_SESSION['usertype'] = $user['type'];
if($_SESSION['usertype'] == 'admin')
{
//admin content here
}
elseif ($_SESSION['usertype']) == 'standard')
{
echo 'you must be an admin to see this page';
}
PS:不确定它能解决你的问题