迁移到实时网站后,会话变量被销毁

时间:2019-03-10 20:29:13

标签: php html http session https

我刚刚将网站从本地WAMP服务器迁移到1and1上的实时HTTPS服务器。它可以在本地服务器上完美运行,但是在运行服务器上,当我尝试登录时,会话变量将被破坏。我知道数据库可以正常工作,并且经过一些测试,所有查询都可以成功运行。

问题是当我运行登录脚本时正在创建会话变量,但是一旦页面重新加载并运行“会话检查”,该变量就不再存在。因此,该站点只是在不满足if条件的情况下重新加载登录表单。

这是两个脚本的代码。我不知道为什么会这样,因为整个网站都是通过HTTPS运行的,所以这与HTTP / HTTPS等无关。

登录脚本

<?php

date_default_timezone_set("Europe/London");
require("db_connect.php");

if ($sql)
{
    $email = $_POST['userEmail'];
    $password = $_POST['userPassword'];

    $checkDetails = mysqli_query($sql, "SELECT * FROM users WHERE email='$email'");

    while ($details = mysqli_fetch_array($checkDetails))
    {
        $hashedPassword = $details['password'];

        if(password_verify($password, $hashedPassword))
        {
            //Passwords Match

            //Update last login time in the database
            $now = date("Y-m-d H:i:s");
            $lastLoginQuery = mysqli_query($sql, "UPDATE users SET lastLogin='$now' WHERE email='$email'");

            if ($lastLoginQuery)
            {
                //Initialise session
                session_start();
                $_SESSION['user'] = $email;
                header("Location: ../");
            }
            else
            {
              echo "There was an error logging you in. Please try again!";
            }
        }
        else
        {
            echo "The details you entered are incorrect. Please return to the login page. If the problem persists, contact an administrator.";
        }
    }
}
else
{
    echo "There was a problem connecting to the database";
}

?>

会话检查脚本

<?php

//Check if a session exists and load the page if it does

session_start();

if (isset($_SESSION['user']))
{
    //Check if the session has timed out
    if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 1800))
    {
        //Last user action performed more than 30 minutes ago. Log out now.
        session_unset();
        session_destroy();
        header("Location:./");
    }

    //If the session hasnt timed out. Reset the last activity time.
    $_SESSION['LAST_ACTIVITY'] = time();

    //Continue to load content
    include('./includes/main.php');
}
else
{
    //  Load login page
    include('./includes/login_form.php');
}

?>

2 个答案:

答案 0 :(得分:0)

会话开始必须是脚本中的第一个调用。 https://www.w3schools.com/php/php_sessions.asp

 <?php
   session_start();

   date_default_timezone_set("Europe/London");
    require("db_connect.php");

等...

答案 1 :(得分:0)

通过添加其他session_start()来解决此问题;直接在任何html之前的index.php文件的开头。似乎很奇怪,如果没有这些,login和session_check脚本将无法工作,因为它们也具有session_start();。在他们里面。