$ _SESSION困难

时间:2009-08-20 15:53:42

标签: php redirect login session

我正在创建一个登录脚本,将$userid变量的值存储到$_SESSION["userid"],然后将用户重定向回主页面(一个问题是如何将它们发送回原来的位置) ?)。

然而,当我回到该页面时,我回显session_id()$_SESSION["userid"]的值,只显示会话ID。在我看来,我的重定向页面可能需要在顶部,但如果这是真的,那么每次我回显到回显它的页面时,我回复的session_id都会改变。这是脚本:

    <?php
session_start();
include_once("db_include.php5");
doDB();
//check for required fields from the form
if ((empty($_POST['username']) && empty($_POST['email'])) || empty($_POST['password'])) {
header("Location: loginform.php5");
exit;
}   else if($_POST["username"] && $_POST["password"]){

    //create and issue the query
    $sql = "SELECT id FROM aromaMaster WHERE username='".$_POST["username"]."' AND password=PASSWORD('".$_POST["password"]."')";
    $sql_res =mysqli_query($mysqli, $sql) or die(mysqli_error($mysqli));

    //get the number of rows in the result set; should be 1 if a match
    if(mysqli_num_rows($sql_res) != 0) {
      //if authorized, get the userid
      while($info = mysqli_fetch_array($sql_res)) {
        $userid = $_info["id"];
      }
      //set session variables
      $_SESSION['userid'] = $userid;

      mysqli_free_result($sql_res);
      //redirect to main page
      header("Location: loginredirect.php5");
      exit; }
    } else if($_POST["email"] && $_POST["password"]) {

          //create and issue the query
    $sql = "SELECT id FROM aromaMaster WHERE email='".$_POST["email"]."' AND password=PASSWORD('".$_POST["password"]."')";
    $sql_res =mysqli_query($mysqli, $sql) or die(mysqli_error($mysqli));

    //get the number of rows in the result set; should be 1 if a match
    if(mysqli_num_rows($sql_res) != 0) {

      //if authorized, get the userid
      while($info = mysqli_fetch_array($sql_res)) {
        $userid = $_info["id"];
      }
      //set session variables
      $_SESSION['userid'] = $userid;

      mysqli_free_result($sql_res);

      //redirect to main page
      header("Location: loginredirect.php5");
      exit;}
      } else {
      //redirect back to login form
      header("Location: loginform.php5");
      exit;
    }
    mysqli_close($mysqli);
?>

3 个答案:

答案 0 :(得分:3)

你这样做:

while($info = mysqli_fetch_array($sql_res)) {
    $userid = $_info["id"];
}

您应该在哪里执行此操作:

while($info = mysqli_fetch_array($sql_res)) {
    $userid = $info["id"];
}

答案 1 :(得分:1)

您需要调用session_write_close()来存储会话数据更改。

答案:如果浏览器填写了<{1}},您可以使用$SERVER["HTTP REFERER"]重定向

答案 2 :(得分:1)

确保:

   <?php
   session_start();

位于每页的顶部。

此外,您可以通过注释掉重定向并回显您正在设置的值来进行测试,以确保您正在检索/存储正确的值。