4

成功登录后,我正在保存会话变量。

当用户转到应用程序中的不同页面时,即使我没有明确销毁会话,会话也会消失。我该如何解决?

这是会话似乎消失的页面。

<?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();
?>
4

2 回答 2

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'];

...
于 2012-10-25T23:47:46.563 回答
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因此您仍然可以始终使用会话,而无需将其与某些东西混合。

于 2012-10-25T21:49:21.040 回答