我定义了一个会话类,它使用$sessionVars数组中$_POST变量的值。当用户登录到创建会话类的新实例时,构造函数将设置会话变量。我检查了一下,这是正常工作的。问题:当我试图从不同的页面访问这些变量会话显示,它没有开始,这些变量是未定义的。困惑,因为我认为$_SESSION是一个超级全局意味着它可以访问所有的时间(I。(范围不重要)。当我试图访问$_SESSION变量时,我怀疑我做错了什么,因为它们在一个类中。我很感激任何帮助……提前感谢。
class userSession{
public function __construct($sessionVars){
session_start();
$_SESSION['userEmail']=$sessionVars['user'];
$_SESSION['userID']=$sessionVars['userID'];
$_SESSION['userFolder']='users/user_'.$_SESSION['userID'];
}
/*just for housekeeping. not used in application*/
function showvars(){
echo $_SESSION['userEmail'].'<br><br>';
echo $_SESSION['userID'].'<br><br>';
echo $_SESSION['userFolder'];
$sessionID=session_id();
echo '<br><br>'.$sessionID;
}
}//**END USER SESSION
/*This is the login script that calls the session*/
include 'library.php';
$show=new render;
$show->index();
if(!isset($_POST['login']) ){
$show->usrLogin();
} else{
if(!empty($_POST['email'])){
$postVars=array('user'=>$_POST['email'],'pass'=>$_POST['password']);
$user=new user();
$data=$user->loginUser($postVars);
$currSession=new userSession($data);
}else{
die('No data in POST variable');}
}
/*file upload that needs the session[userFolder] variable*/
function file_upload(){
$userFolder=&$_SESSION['userFolder'];
echo '<hr>userFolder is : '.$userFolder;
function do_upload(){
if(!empty( $_FILES) ){
echo $userFolder.'<hr>';
$tmpFldr=$_FILES['upFile']['tmp_name'];
$fileDest=$userFolder.'/'.$_FILES['upFile']['name'];
if(move_uploaded_file($tmpFldr,$fileDest)){
echo 'file(s) uploaded successfully';
}
else{
echo 'Your file failed to upload<br><br>';
}
return $fileDest; //returns path to uploaded file
} else{die( 'Nothing to upload');}
}//END FUNCTION DO_UPLOAD,
/*Perform upload return file location*/
$fileLoc=do_upload();
return $fileLoc;
}
您需要在使用会话的每个页面上实例化该类的对象(或手动启动会话)。另外,您将不需要该构造函数,而是使用其他方式设置变量。这只是为了说明它如何与您当前的代码一起工作,还有更好的方法:
class userSession {
public function __construct(){
session_start();
}
function set_login_vars($sessionVars){
$_SESSION['userEmail']=$sessionVars['user'];
$_SESSION['userID']=$sessionVars['userID'];
$_SESSION['userFolder']='users/user_'.$_SESSION['userID'];
}
}
//page1.php
$session = new userSession;
$session->set_login_vars($loginVars);
//page2.php
//you need to start the session, either with the class
$session = new userSession;
//or session_start();
print_r($_SESSION);