成功登录后,我正在保存会话变量。
当用户访问应用程序中的不同页面时,即使我没有明确销毁会话,会话也会消失。我该如何解决这个问题?
这是一个会话似乎消失的页面。
<?php
include 'core/init.php';
include 'core/sendmessage.php';
$user_info = $_SESSION['user_id'];
$getUser = mysql_query("SELECT * FROM users WHERE user_id = ".$uid);
$user_info = array();
while($currentRow = mysql_fetch_array($getUser)){
$user_info['firstname'] = $currentRow['first_name'];
$user_info['lastname'] = $currentRow['last_name'];
$user_info['username'] = $currentRow['username'];
}
?>
在core/init.php
内,我有会话启动方法。
<?php
session_start();
require 'database/connect.php';
require 'functions/users.php';
require 'functions/general.php';
if (logged_in() === true) {
$user_data = user_data($_SESSION['user_id'],'first_name','last_name','username');
}
$errors = array();
?>
答案 0 :(得分:2)
session_start()根据通过GET或POST请求传递的会话标识符创建会话或恢复当前会话,或者 通过cookie传递。 (访问 PHP: session_start )
在每个页面的开头添加session_start()
(在<?php
标记之后)。
在你的情况下:
<?php
if(!isset($_SESSION)) session_start(); //--> ADD this line
include 'core/init.php';
include 'core/sendmessage.php';
$user_info = $_SESSION['user_id'];
...
答案 1 :(得分:0)
你应该尝试为所有这些使用不同的名称,因为我认为将一个会话中使用的值用于另一个值(因为它将替换旧的值)并且使会话在您下次访问该页面时消失。会话仅创建一次。
<?php
include 'core/init.php';
include 'core/sendmessage.php';
$user_info = $_SESSION['user_id'];
$getUser = mysql_query("SELECT * FROM users WHERE user_id = ".$uid);
$userinfo = array(); //I changed $user_info to $userinfo so it doesn't get mixed with the session.
while($currentRow = mysql_fetch_array($getUser)){
//I removed the underscore
$userinfo['firstname'] = $currentRow['first_name'];
$userinfo['lastname'] = $currentRow['last_name'];
$userinfo['username'] = $currentRow['username'];
}
?>
即使我没有测试它,它现在应该没问题了。
我刚刚将数组更改为$userinfo
,因此您仍然可以始终使用该会话,而不会将其与某些内容混合。