会话类中的变量未传递给新页面

时间:2014-05-08 20:23:22

标签: php session

我定义了一个会话类,它使用名为$ sessionVars的数组中$ _POST变量的值。当用户登录时,会创建一个新的会话类实例,构造函数会设置会话变量。我检查这是否正常工作。问题:当我尝试从不同的页面访问这些变量时,会话显示它不是开始,这些变量是未定义的。困惑的原因我认为$ _SESSION是一个超级全球意味着它一直可访问(即范围并不重要)。当我尝试访问$ _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;
  }

1 个答案:

答案 0 :(得分:0)

您需要在使用会话的每个页面上实例化此类的对象(或手动启动会话)。此外,您不需要该构造函数,而是需要其他一些设置变量的方法。这只是为了说明它如何与您当前的代码一起使用,有更好的方法:

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);