PHP $-SESSION变量在新页面上消失并返回空
作者:互联网
我遇到了Sessions变量的问题.自从我从mysqli切换到PDO.它与mysqli一起运行良好,但自从我改用PDO后,这个问题现在已经出现了.
我正在尝试登录,我有一个区域,我想确保用户只能看到,如果用户登录.登录工作正常,但一旦我被提到我的索引文件,我由于登录功能,看不到任何东西.我可以看到$_SESSION变量被填充,但是一旦我重定向到另一个文件,$_SESSION变量就会消失,我得到一个空数组:
Array
(
)
process_login.php
require_once('../inc/user.inc.php'); // here i have all my functions
$user = new User(); // New Instance of my User Class
$user -> sec_session(); // selfmade session function. I use start_session() in this function
if (isset($_POST['email'], $_POST['p'])) {
$email = filter_var($_POST['email'], FILTER_SANITIZE_STRING);
$password = filter_var ($_POST['p'], FILTER_SANITIZE_STRING);
$login = $user -> login_user($email, $password);
if ($login) {
// Login sucessful
//print("<pre>".print_r($_SESSION,true)."</pre>"); //Here i get my $_SESSION variable printed out and it works. I see it is filled.
header('Location: ../index.php');
exit();
}
的index.php
<?php
$title = 'Index';
$currentPage = 'Dashboard';
include('php/head.php');
require_once('../inc/user.inc.php');
$user = new User();
$user -> sec_session(); // here i call my session function again. Note: session_start() is included in this function
print("<pre>".print_r($_SESSION,true)."</pre>"); //Now The Array is empty?!?
?>
user.inc.php – sec_session函数
protected function sec_session() {
$session_name = 'sec_session_id';
$secure = SECURE;
$httponly = true;
if (ini_set('session.use_only_cookies', 1) === FALSE) {
header("Location: ../error.php?err=Could not initiate a safe session (ini_set)");
exit();
}
$cookieParams = session_get_cookie_params();
session_set_cookie_params($cookieParams["lifetime"],
$cookieParams["path"],
$cookieParams["domain"],
$secure,
$httponly);
session_name($session_name);
session_start();
session_regenerate_id();
}
登录时,我在登录功能中将会话设置为以下内容:
if ($db_password == $password) {
$user_browser = $_SERVER['HTTP_USER_AGENT'];
$user_id = preg_replace("/[^0-9]+/", "", $user_id);
$_SESSION['user_id'] = $user_id;
$username = preg_replace("/[^a-zA-Z0-9_\-]+/",
"",
$username);
$_SESSION['username'] = $username;
$_SESSION['login_string'] = hash('sha512',
$password . $user_browser);
return true;
}
上面的工作都很好,但只有消失,当我登陆我的index.php,我知道有什么东西,但我不知道它是什么.
解决方法:
您使用http或https访问本地网站吗?如果您使用安全cookie,PHP将无法在http下读取它们,而是使用新cookie启动新会话,切换到https可以解决此问题.
从sec_session函数看,您正在使用安全cookie($secure = SECURE;),那么您的浏览器会话是否使用HTTPS?如果您使用带有安全cookie的HTTP,您将在每个页面上启动一个新会话,并且无法访问现有会话变量.
最好的解决方案是使用https访问您的本地站点,就像访问您的实际站点一样,但是如果您关闭本地站点的安全cookie设置也是如此.
标签:php,session-variables 来源: https://codeday.me/bug/20191003/1846180.html