我正在尝试构建一个门户网站,其中我有两个“页面”,一个进入正常用户,另一个进入管理员进入的/ admin。我正在讨论会话但问题是,一旦用户登录,他/她甚至可以访问管理区域,反之亦然。那是为什么?
我该怎样阻止它?
感谢。
check_login
<?php
define(DOC_ROOT,dirname(__FILE__)); // To properly get the config.php file
$username = $_POST['username']; //Set UserName
$password = $_POST['password']; //Set Password
$msg ='';
if(isset($username, $password)) {
ob_start();
include(DOC_ROOT.'/config.php'); //Initiate the MySQL connection
// To protect MySQL injection (more detail about MySQL injection)
$myusername = stripslashes($username);
$mypassword = stripslashes($password);
$myusername = mysqli_real_escape_string($dbC, $myusername);
$mypassword = mysqli_real_escape_string($dbC, $mypassword);
$sql="SELECT * FROM login_admin WHERE user_name='$myusername' and user_pass=SHA1('$mypassword')";
$result=mysqli_query($dbC, $sql);
// Mysql_num_row is counting table row
$count=mysqli_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1){
// Register $myusername, $mypassword and redirect to file "admin.php"
session_register("admin");
session_register("password");
$_SESSION['name']= $myusername;
header("location:index.php");
}
else {
$msg = "Wrong Username or Password. Please retry";
header("location:login.php?msg=$msg");
}
ob_end_flush();
}
else {
header("location:login.php?msg=Please enter some username and password");
}
?>
我在每页前插入的内容:
<?php
session_start(); //Start the session
define(ADMIN,$_SESSION['name']); //Get the user name from the previously registered super global variable
if(!session_is_registered("admin")){ //If session not registered
header("location:login.php"); // Redirect to login.php page
}
else //Continue to current page
header( 'Content-Type: text/html; charset=utf-8' );
?>
答案 0 :(得分:1)
制作两个会话变量,如
$_SESSION['user']//can access only one page
$_SESSION['admin']//can access both
并按isset($_session['user'])
或isset($_session['admin'])
答案 1 :(得分:1)
用户成功授权后,检查他是管理员还是普通用户。因此,对于管理员用户,您可以定义管理员会话变量
$_SESSION['admin_user'] = True
然后在显示管理部分之前,只需检查用户是否具有正确的权限。
if ($_SESSION['admin_user']) {
// display admin content
}
else {
print("Not available, you need admin privilege.");
}
因此,根据您的代码,我会将其修改为类似的内容:
<?php
session_start(); //Start the session
if( isset($_SESSION['admin']) && $_SESSION['admin_user'] ){ //If session registered and admin
header( 'Content-Type: text/html; charset=utf-8' );
// more content
}
else
header("location: login.php"); // Redirect to login.php page
?>
同样session_register已被弃用,并且已从php 5.4中删除,因此请改用$ _SESSION ['variable_name']。
答案 2 :(得分:-1)
这是你应该做的:
// and 956 in ur db is admin, user enters the userID in login
if(_SESSION['userID']=="956")
{
redirect_to("localhost/admin.php");
}
else
{
redirect_to ("localhost/home.php");
}