php - 迁移到实时网站后,会话变量被销毁
问题描述
我刚刚将我的网站从本地 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');
}
?>
解决方案
通过添加额外的 session_start() 解决了这个问题;直接在 index.php 文件的开头任何 html 之前。如果没有这个,login 和 session_check 脚本将无法工作,这似乎很奇怪,因为它们也有 session_start(); 在他们里面。
推荐阅读
- flutter - Flutter - 在底部导航栏上方添加一行
- vue.js - 如何在 vue 3 (Danfo.js) 中导入 NPM 包
- python - Python中带有返回函数的循环输入
- flutter - 壁纸应用程序,不工作图片库保护程序
- r - 为什么在计算 R 的平均值时会收到此错误消息?我该如何解决?
- dialog - Vuetify Grid 系统在我的对话框中添加水平滚动条
- sql - 如何在SQL中的varchar字符串范围内获取值
- python - 如何有效地从 python 字典中删除一些元素?
- kubernetes - Kubernetes Statefulset - 副本服务
- google-cloud-platform - 通过 IAP 验证从 GCE 到 BigQuery 的请求