在PHP中创建两个不同的会话

时间:2012-07-02 05:58:24

标签: php session session-variables

我正在尝试创建两个单独的会话 - 一个用于用户是管理员而另一个用户是作者。 $ type存储类型为枚举(可以是作者或管理员)。但是我的代码甚至为管理员创建了作者会话。我是PHP和MySQL的新手。有人可以告诉我我的代码中的错误在哪里。

<?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>

提前非常感谢你。

4 个答案:

答案 0 :(得分:1)

尝试为您的权限使用角色。

一般来说,你只有一个会话。我的意思是你没有两个叫做_SESSION的变量。

使用角色的概念,您只需检查用户是否有权做某事。

答案 1 :(得分:0)

在会话中注册var session_start()之前,您必须在代码的第一部分调用$_SESSION['type']

答案 2 :(得分:0)

我认为没有你的代码接缝。 我没有看到你在哪里调用数据库 你在那里有什么

所以这就是你拍摄麻烦的方法

  while ($info = mysql_fetch_array($result)) {
      $type =$info['type'];
      echo $type . '<br />';
  }

OR

  echo '<pre>';
  while ($info = mysql_fetch_array($result)) {
      $type =$info['type'];
      print_r($info);
  }
  echo '</pre>';

如果你从未在那里看过管理员,那么它必须是'admin'而不是Admin或ADMIN;然后问题出在您的数据库中。您没有admin作为管理员定义,或拼写正确。

顺便说一下。看看我格式化得多好。这种方式更容易阅读 如果你不这样做,编码器就不会看你的代码。

答案 3 :(得分:0)

尝试使用session_regenerate_id();方法创建不同的会话ID。