在PHP中创建两个不同的会话
我正在尝试创建两个单独的会话-一个用于用户是否为admin,另一个用于用户是否为author$将存储类型键入为enum(可以是author或admin)。但我的代码甚至为管理员创建了author会话。我不熟悉PHP和MySQL。谁能告诉我代码中的错误在哪里吗在PHP中创建两个不同的会话,php,session,session-variables,Php,Session,Session Variables,我正在尝试创建两个单独的会话-一个用于用户是否为admin,另一个用于用户是否为author$将存储类型键入为enum(可以是author或admin)。但我的代码甚至为管理员创建了author会话。我不熟悉PHP和MySQL。谁能告诉我代码中的错误在哪里吗 <?php include("dbconnect.php"); $con= new dbconnect(); $con->connect(); //create and issue the query $sql = "SELEC
<?php
include("dbconnect.php");
$con= new dbconnect();
$con->connect();
//create and issue the query
$sql = "SELECT type FROM users WHERE username = '".$_POST["username"]."' AND password = PASSWORD('".$_POST["password"]."')";
$result = mysql_query($sql);
//get the number of rows in the result set; should be 1 if a match
if (mysql_num_rows($result) == 1) {
$type_num=0;
//if authorized, get the values
while ($info = mysql_fetch_array($result)) {
$type =$info['type'];
}
if($type == "admin")
{
$_SESSION['type']=1;
$u = 'welcome.php';
header('Location: '.$u);
}
else
{
$_SESSION['type']=$type_num;
$u = 'welcome.php';
header('Location: '.$u);
}
}
else {
//redirect back to loginfailed.html form if not in the table
header("Location: loginfailed.html");
exit;
}
?>
我的welcome.php如下所示
<?php
session_start();
?>
<html>
<body>
<h2>Welcome.</h2>
<?
if($_SESSION['type']==1){
echo "You are of the usertype Admin and your session id is ";
echo session_id();
}
else {
echo "You are of the usertype Author and your session id is ";
echo session_id();
}
?>
</body>
</html>
欢迎
提前非常感谢。您必须在代码的第一部分调用
session\u start()
,然后才能在会话中注册var$\u session['type']
尝试使用角色作为您的权限
一般来说,您只有一个会话。我的意思是你没有两个变量叫做_SESSION
有了角色的概念,你可以简单地检查用户是否有做某事的权限。不,我认为你的代码很好。 我看不出你在哪里调用数据库 那里面有什么 这就是你如何解决问题的方法
while ($info = mysql_fetch_array($result)) {
$type =$info['type'];
echo $type . '<br />';
}
while($info=mysql\u fetch\u array($result)){
$type=$info['type'];
echo$type.“
”;
}
或
echo';
而($info=mysql\u fetch\u数组($result)){
$type=$info['type'];
打印(信息);
}
回声';
如果你从来没有看到管理员在那里,它必须是'管理员'不是管理员或管理员;那么问题就出在你的数据库里了。您没有定义为admin或拼写正确的admin
顺便说一下。看看我的格式有多好。这样读起来更容易。如果您不这样做,编码人员将不会查看您的代码。尝试使用
session\u regenate\u id()代码>创建不同会话ID的方法。此时您的$\u会话中有什么内容?如果它完全为空,我也不会感到惊讶,因为我在页面上没有看到设置变量的session\u start()
(每个访问会话的页面都需要此调用)。顺便说一下,通过简单的盲SQL注入,在不知道正确密码的情况下登录非常简单。试试用户名:admin'——你真的不需要这样做。是的,您的代码中存在SQL注入漏洞,请参阅和。谢谢Marcio。这很有帮助。但我还有一个问题。每次我测试的时候,我都会为任何作者或管理员获得相同的会话id。我看不太对。这就是它应该的方式吗?@user1479431,每个会话必须有一个唯一的ID,可能在创建另一个会话之前您没有破坏该会话。您必须使用,将其放在文件welcome.php
的末尾,仅用于测试目的。或者使用不同的浏览器。您还可以删除浏览器cookie@user1479431,在调用session_destroy()之前,您必须在同一个文件中调用session_start(),您正在这样做吗?是的!我在welcome.php的末尾添加了session_destroy()(不是在第一部分,因为我当时不需要销毁会话),但是更多信息会有所帮助。你是对的。我的答案是,在这种情况下,只是一个如何使其更好的想法。在手机上也很难解释。是的,我给a+1是因为我同意你的观点,但从问题和代码来看,OP可能不知道你所说的角色是什么:)
echo '<pre>';
while ($info = mysql_fetch_array($result)) {
$type =$info['type'];
print_r($info);
}
echo '</pre>';