分别管理会话文件以包含在所有文件中

时间:2017-11-17 15:02:45

标签: php session

记录后,会话将开始。所以我必须管理所有其他文件中的session.php来管理会话。这是我的登录文件:

<?php 
    if(isset($_POST['submit']))
    {
        include("connect.php");
        $user=mysqli_real_escape_string($con, $_POST['email']);
        $pass=mysqli_real_escape_string($con, $_POST['password']);
        $sql="SELECT * FROM users WHERE email='".$user."' AND password='".$pass."' ";
        $query=mysqli_query($con, $sql) or die(mysqli_error($con));
        $count=mysqli_num_rows($query);
        if($count==1)
        {   
            $row=mysqli_fetch_array($query);
            session_start();
            $_SESSION['user_id']=$row['uid'];
        }
        else {
            header("location:../index.php?error=1");
        }
        if(isset($_SESSION["user_id"])) {   
            header("location:../home.php");
        }
    }    
?>

在sessions.php中:

<?php
    session_start();
    session_regenerate_id();
    if($_SESSION["user_id"]) 
    {
        include("connect.php");
        $m1 = "select * from users where uid='".$_SESSION['user_id']."'";
        $m2 = mysqli_query($con, $m1);
        $m3 = mysqli_fetch_array($m2);
        $_SESSION['username'] = $m3['fname'].' '.$m3['lname'];
    } 
    else 
    if(!isset($_SESSION['user_id']))
    {
        header("location:index.php");
    }
?>

当会话在login.php本身启动时,我在sessions.php中遇到错误&#39;会话已经启动&#39;。但是,如果我删除session_start();,它会重定向到index.php(登录表单)。我很迷惑。

有人可以帮助我吗?

2 个答案:

答案 0 :(得分:0)

许多评论者指出了所问问题的问题。我无法发表评论,因此我将提供一些建议。

die(mysqli_error($con))

这些错误应转到日志文件,而不显示给用户查看。有人可以通过阅读错误消息并利用它们来发现系统中的漏洞。不要让他们容易!

答案 1 :(得分:0)

<?php 
        session_start();
        $user_id =  $_SESSION['user_id'];
        if(isset($_POST['submit']))
        {
            include("connect.php");
            $user=mysqli_real_escape_string($con, $_POST['email']);
            $pass=mysqli_real_escape_string($con, $_POST['password']);
            $sql="SELECT * FROM users WHERE email='".$user."' AND password='".$pass."' ";
            $query=mysqli_query($con, $sql) or die(mysqli_error($con));
            $count=mysqli_num_rows($query);
            if($count==1)
            {   
                $row=mysqli_fetch_array($query);

                $_SESSION['user_id']=$row['uid'];
            }
            else {
                header("location:../index.php?error=1");
            }
            if(isset($_SESSION["user_id"])) {   
                header("location:../home.php");
            }
        }    
    ?>

在sessions.php中:

<?php
    session_start();
    session_regenerate_id();
    if($user_id) 
    {
        include("connect.php");
        $m1 = "select * from users where uid='".$user_id."'";
        $m2 = mysqli_query($con, $m1);
        $m3 = mysqli_fetch_array($m2);
        $_SESSION['username'] = $m3['fname'].' '.$m3['lname'];
    } 
    else 
    if(!isset($user_id))
    {
        header("location:index.php");
    }
?>